Maizere Pathak.Nepal
Maizere Pathak.Nepal

Reputation: 2413

Javascript Array prototype

Since Array.prototype itself is an array([]) reference here,if we have to replace native prototype how can we place literal object instead we need to place literal array isn't it?

Array.prototype=[]

Upvotes: 0

Views: 567

Answers (2)

Ted Hopp
Ted Hopp

Reputation: 234795

There's no point in assigning a new array to 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.

If you want to replace (hide) a native instance method of Array (e.g., push), just assign the new method to the appropriate property:

Array.prototype.push = . . .;

Also, see this answer for how you might extend a native method (such as 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...)

Upvotes: 2

Mike Samuel
Mike Samuel

Reputation: 120516

EcmaScript 5, the latest version of JavaScript, changed the meaning of

[]

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.

The EcmaScript 5 specification says

11.1.4 Array Initialiser

...

The production ArrayLiteral : [ Elisionopt ] is evaluated as follows:

  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.

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.

Upvotes: 2

Related Questions