相关疑难解决方法(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万
查看次数

使用"Object.create"而不是"new"

Javascript 1.9.3/ECMAScript 5介绍Object.create道格拉斯·克罗克福德等人长期以来一直在倡导.如何new在下面的代码中替换Object.create

var UserA = function(nameParam) {
    this.id = MY_GLOBAL.nextId();
    this.name = nameParam;
}
UserA.prototype.sayHello = function() {
    console.log('Hello '+ this.name);
}
var bob = new UserA('bob');
bob.sayHello();
Run Code Online (Sandbox Code Playgroud)

(假设存在MY_GLOBAL.nextId).

我能想到的最好的是:

var userB = {
    init: function(nameParam) {
        this.id = MY_GLOBAL.nextId();
        this.name = nameParam;
    },
    sayHello: function() {
        console.log('Hello '+ this.name);
    }
};
var bob = Object.create(userB);
bob.init('Bob');
bob.sayHello();
Run Code Online (Sandbox Code Playgroud)

似乎没有任何优势,所以我想我没有得到它.我可能过于新古典主义了.我应该如何使用MY_GLOBAL.nextId创建用户'bob'?

javascript constructor new-operator object-create

364
推荐指数
8
解决办法
17万
查看次数