0

I read somewhere that :

var o = new Array();

is in effect doing the following:

var o = {};
o.__proto__ = Array.prototype;
Array.call(o)

My question is what is Array.call(o) doing?

If I had o2 = {};

what does Array.call(o2) do?

TIA JD

1 Answer 1

1

The new operator in JavaScript has three essential tasks. First, it creates a new empty object. Next, it sets the new object’s proto property to match the prototype property of the function being invoked. Finally, the operator invokes the function and passes the new object as the “this” reference

The function here is the array constructor Array() So the first step here is creating an empty object

var o = {};

The second step is setting the proto property

o.__proto__ = Array.prototype;

And then, the final step, you have the invocation of the function, and passing the new object as reference

Array.call(o)
Sign up to request clarification or add additional context in comments.

5 Comments

Thanks. It is just that I am having trouble understanding what the invocation of the function Array.call() is doing? Are we saying that in other methods (say we had Method2() {uses "this";}) the reference to "this" reference will be o? If so how is does this work in code?
For example, if you have a variable some_variable and you have a method Method2, doing Method2.call(some_variable) will be like replacing this with some_variable in the call so you"ll have Method2() {uses some_variable;} and if you have Method2(some_argument) {uses this}, you can use call method by doing Method2.call(some_variable, some_argument)
Thanks, I am starting to get my head around how it works. Just one more questions, any idea what the code for Array() (constructor function) looks like?
No, sorry, I have no Idea. :(
you can check the webkit code here svn.webkit.org/repository/webkit/trunk/Source/JavaScriptCore/… check the files ArrayConstructor, ArrayPrototype and JSArray (.cpp and .h), it might help

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.