简体   繁体   English

Javascript数组原型

[英]Javascript Array prototype

由于Array.prototype本身是此处的array([]) 引用 ,如果我们必须替换本机原型,我们如何放置文字对象,而我们需要放置文字数组,不是吗?

Array.prototype=[]

There's no point in assigning a new array to Array.prototype . 将新数组分配给Array.prototype没有意义。 It's usually a read-only property and the assignment will fail silently. 它通常是一个只读属性,分配将自动失败。

> a = []
[]
> a === Array.prototype
false
> Array.prototype = a
[]
> a === Array.prototype
false

Even if the assignment were to succeed, the replacement array would of necessity have been created with the original prototype in place. 即使分配成功,也必须在原始原型到位的情况下创建替换阵列。 Thus, the original prototype would be the [[prototype]] of the new prototype object and all the native methods would still be found in the prototype chain of any array created after the assignment. 因此,原始原型将是新原型对象的[[prototype]] ,并且所有本机方法仍将在分配后创建的任何数组的原型链中找到。

If you want to replace (hide) a native instance method of Array (eg, push ), just assign the new method to the appropriate property: 如果要替换(隐藏) Array的本机实例方法(例如push ),只需将新方法分配给适当的属性:

Array.prototype.push = . . .;

Also, see this answer for how you might extend a native method (such as push ). 另外,请参阅此答案以了解如何扩展本机方法(例如push )。 (Unless you're just extending a native method in some way, I can't imagine a use case where this is anything other than a really bad thing to do. Even then...) (除非您只是以某种方式扩展了本机方法,否则我无法想象一个用例,除了要做一件非常糟糕的事情外,这还没有什么。即使如此...)

EcmaScript 5, the latest version of JavaScript, changed the meaning of 最新版本的JavaScript EcmaScript 5改变了

[]

from

 new Array()

to create using the original Array constructor instead of looking up the name Array in scope as earlier versions of JavaScript did. 使用原始Array构造函数进行创建,而不是像早期版本的JavaScript那样在范围内查找名称Array

The EcmaScript 5 specification says EcmaScript 5规范

11.1.4 Array Initialiser 11.1.4数组初始化器

... ...

The production ArrayLiteral : [ Elision opt ] is evaluated as follows: 生产ArrayLiteral:[Elision opt ]的评估如下:

  1. Let array be the result of creating a new object as if by the expression new Array() where Array is the standard built-in constructor with that name. 令array为创建新对象的结果,就像通过表达式new Array() ,其中Array是具有该名称的标准内置构造函数。

The bolded text is new in EcmaScript 5, and means that the meaning of [] is not affected by any subsequent modifications to the Array global or its members including its prototype. 粗体文本是EcmaScript 5中的新增内容,表示[]的含义不受Array全局或其成员(包括其原型)的任何后续修改的影响。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM