我最近偶然发现了 JavaScript 中的 Object.create()
方法,并尝试推断它与使用 new SomeFunction()< 创建对象的新实例有何不同
,以及当您想要使用其中之一而不是另一个时。
考虑以下示例:
var test = {
val: 1,
func: function() {
return this.val;
}
};
var testA = Object.create(test);
testA.val = 2;
console.log(test.func()); // 1
console.log(testA.func()); // 2
console.log('other test');
var otherTest = function() {
this.val = 1;
this.func = function() {
return this.val;
};
};
var otherTestA = new otherTest();
var otherTestB = new otherTest();
otherTestB.val = 2;
console.log(otherTestA.val); // 1
console.log(otherTestB.val); // 2
console.log(otherTestA.func()); // 1
console.log(otherTestB.func()); // 2
请注意,在这两种情况下都观察到相同的行为。在我看来,这两种情况之间的主要区别是:
Object.create()
中使用的对象实际上形成了新对象的原型(prototype),而在new Function()
中声明的属性/函数则不会形成原型(prototype)。- 您无法像使用函数语法那样使用
Object.create()
语法创建闭包。考虑到 JavaScript 的词法(相对于 block )类型范围,这是合乎逻辑的。
以上说法正确吗?我错过了什么吗?你什么时候会使用其中一种而不是另一种?
编辑:链接到上述代码示例的 jsfiddle 版本:http://jsfiddle.net/rZfYL/
最佳答案
非常简单地说,new X
是 Object.create(X.prototype)
并另外运行构造函数
函数。 (并让构造函数
有机会返回
应该是表达式结果的实际对象,而不是this
。)
就是这样。 :)
其余的答案只是令人困惑,因为显然没有其他人阅读 new 的定义。任何一个。 ;)
关于javascript - 了解 Object.create() 和 new SomeFunction() 之间的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41343037/