相关疑难解决方法(0)

理解Object.create()和new SomeFunction()之间的区别

我最近Object.create()在JavaScript中偶然发现了这个方法,并试图推断它与创建一个对象的新实例有什么不同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
Run Code Online (Sandbox Code Playgroud)

请注意,在两种情况下都观察到相同的行为.在我看来,这两种情况之间的主要区别是:

  • Object.create()实际使用的对象实际上形成了新对象的原型,而在new …

javascript prototype object-create

372
推荐指数
10
解决办法
12万
查看次数

标签 统计

javascript ×1

object-create ×1

prototype ×1