理解Object.create()和新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
Object.create()
new Function()
Object.create()
阿晨1998
慕姐4208626
至尊宝的传说
随时随地看视频慕课网APP
相关分类