【问题标题】:What EXACTLY is new doing? [duplicate]new 到底在做什么? [复制]
【发布时间】:2014-11-11 16:51:40
【问题描述】:

这将是一个棘手的问题。 有一个构造函数:

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

我们可以创建一个对象:

var obj = new Constructor();
Constructor 中的

this 指的是窗口,但是当调用 new Constructor() 时,正在做一些魔术:现在 this 正在找出它所在的函数的范围(它到底是如何工作的?)并且仅将该范围分配给 obj 会返回它。 所以基本上它正在做类似的事情:

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

谁能告诉我这种在 JS 中创建新对象的机制是如何在低级别工作的?调用 new 时到底在做什么?

【问题讨论】:

标签: javascript prototype proto


【解决方案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"

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-11-26
    • 2020-07-16
    • 1970-01-01
    • 1970-01-01
    • 2016-06-02
    • 2016-02-12
    • 2012-12-24
    相关资源
    最近更新 更多