我最近偶然发现了 Object.create() 方法,我试图推断它与使用 new SomeFunction() ,以及何时您希望使用其中一个而不是另一个。
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
请注意,在这两种情况下观察到相同的行为。在我看来,这两种情况之间的主要区别是:
对象创建()
new Function()
上述说法正确吗?我错过什么了吗?你什么时候会用一个来代替另一个?
编辑:链接到上述代码示例的JSFIDLE版本: http://jsfiddle.net/rZfYL/
简单地说, new X 是 Object.create(X.prototype) 额外运行 constructor 作用(以及 建造师 有机会 return 应该是表达式结果的实际对象,而不是 this .)
new X
Object.create(X.prototype)
constructor
建造师
return
this
就这样。:)
其余的答案只是让人困惑,因为显然没有其他人阅读 new 要么。;)