0

This is going to be a tricky question. Having a constructor:

var Constructor = new function(){
this.a = 'a';
this.b = 'b';
}

we can create an object:

var obj = new Constructor();

this in Constructor refers to window but when calling new Constructor() some magic is being done: now this is finding out the scope of a function it is in (how exactly is it working?) and assigning only that scope to obj returns it. So basically it is doing something like:

var Constructor = new function(){
var this = {some object having variables needed for every object (like __proto__)}    
this.a = 'a';
this.b = 'b';
return this;
}

Can anyone tell me how it is this mechanism of creation of new object in JS is working in low level? What exactly is being done underneath when calling new?

4

1 回答 1

1

“new SomeFunction()”正在创建一个新对象,并以该对象为“this”调用 SomeFunction。

考虑一下:

function SomeFunction() {
    this.hello = "Hello, world";
}
var myObj = new SomeFunction();
myObj.hello; // "Hello, world"

var myObj2 = {};
SomeFunction.call(myObj2);
myObj2.hello; // "Hello, world"
于 2014-09-17T15:10:19.360 回答