Javascript 1.9.3 / ECMAScript 5引入了Object。这是Douglas Crockford等人长期以来一直倡导的。我如何在下面的代码替换新的对象。创建?

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();

(假设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();

似乎没有任何优势,所以我想我没有得到它。我可能太新古典主义了。我应该如何使用Object。创建创建用户“bob”?


当前回答

TL; diana:

new Computer()将调用构造函数Computer(){}一次,而Object.create(Computer.prototype)则不会。

所有的优势都是基于这一点。

关于性能的附加说明:像new Computer()这样的构造函数调用被引擎大量优化,因此它可能比Object.create还要快。

其他回答

与new object相比,使用object. create(…)并没有什么优势。

那些提倡这种方法的人通常会说一些模棱两可的优点:“可伸缩性”,或者“对JavaScript来说更自然”等等。

然而,我还没有看到一个具体的例子来显示这个对象。Create比new有任何优势。相反,它存在一些已知的问题。Sam Elsamman描述了当有嵌套对象并且使用Object.create(…)时会发生什么:

var Animal = {
    traits: {},
}
var lion = Object.create(Animal);
lion.traits.legs = 4;
var bird = Object.create(Animal);
bird.traits.legs = 2;
alert(lion.traits.legs) // shows 2!!!

这是因为Object.create(…)提倡使用数据创建新对象的实践;在这里,动物数据成为狮子和鸟原型的一部分,并在共享时引起问题。当使用new时,原型继承是显式的:

function Animal() {
    this.traits = {};
}

function Lion() { }
Lion.prototype = new Animal();
function Bird() { }
Bird.prototype = new Animal();

var lion = new Lion();
lion.traits.legs = 4;
var bird = new Bird();
bird.traits.legs = 2;
alert(lion.traits.legs) // now shows 4

至于传递给Object.create(…)的可选属性属性,可以使用Object.defineProperties(…)添加。

由于只有一个继承级别,您的示例可能不会让您看到Object.create的真正好处。

该方法允许您轻松实现差异继承,其中对象可以直接从其他对象继承。

在你的userB的例子中,我不认为你的init方法应该是公共的,甚至不存在,如果你在一个现有的对象实例上再次调用这个方法,id和name属性将会改变。

对象。Create允许你使用它的第二个参数初始化对象属性,例如:

var userB = {
  sayHello: function() {
    console.log('Hello '+ this.name);
  }
};

var bob = Object.create(userB, {
  'id' : {
    value: MY_GLOBAL.nextId(),
    enumerable:true // writable:false, configurable(deletable):false by default
  },
  'name': {
    value: 'Bob',
    enumerable: true
  }
});

如您所见,属性可以在Object的第二个参数上初始化。使用类似于object . defineproperties和object . defineproperty方法使用的语法创建一个对象文字。

它允许您设置属性属性(可枚举、可写或可配置),这非常有用。

有时不能使用NEW创建对象,但仍然可以调用create方法。

例如:如果你想定义一个自定义元素,它必须派生自HTMLElement。

proto = new HTMLElement  //fail :(
proto = Object.create( HTMLElement.prototype )  //OK :)
document.registerElement( "custom-element", { prototype: proto } )

new and Object.create serve different purposes. new is intended to create a new instance of an object type. Object.create is intended to simply create a new object and set its prototype. Why is this useful? To implement inheritance without accessing the __proto__ property. An object instance's prototype referred to as [[Prototype]] is an internal property of the virtual machine and is not intended to be directly accessed. The only reason it is actually possible to directly access [[Prototype]] as the __proto__ property is because it has always been a de-facto standard of every major virtual machine's implementation of ECMAScript, and at this point removing it would break a lot of existing code.

对于7ochem上面的回答,对象绝对不应该将它们的原型设置为new语句的结果,不仅因为没有必要多次调用相同的原型构造函数,而且因为如果在创建原型后修改了原型,同一类的两个实例可能会以不同的行为结束。这两个例子都是由于误解和破坏了原型继承链的预期行为而导致的糟糕代码。

当使用Object创建一个实例时,应该写入实例的原型,而不是访问__proto__。创建或随后使用Object。setPrototypeOf,用Object读取。getPrototypeOf或Object.isPrototypeOf。

Also, as the Mozilla documentation of Object.setPrototypeOf points out, it is a bad idea to modify the prototype of an object after it is created for performance reasons, in addition to the fact that modifying an object's prototype after it is created can cause undefined behavior if a given piece of code that accesses it can be executed before OR after the prototype is modified, unless that code is very careful to check the current prototype or not access any property that differs between the two.

Given const X = function (v) { this.v = v }; X.prototype.whatAmI = 'X'; X.prototype.getWhatIAm = () => this.whatAmI; X.prototype.getV = () => this.v; the following VM pseudo-code is equivalent to the statement const x0 = new X(1);: const x0 = {}; x0.[[Prototype]] = X.prototype; X.prototype.constructor.call(x0, 1); Note although the constructor can return any value, the new statement always ignores its return value and returns a reference to the newly created object. And the following pseudo-code is equivalent to the statement const x1 = Object.create(X.prototype);: const x0 = {}; x0.[[Prototype]] = X.prototype; As you can see, the only difference between the two is that Object.create does not execute the constructor, which can actually return any value but simply returns the new object reference this if not otherwise specified.

Now, if we wanted to create a subclass Y with the following definition: const Y = function(u) { this.u = u; } Y.prototype.whatAmI = 'Y'; Y.prototype.getU = () => this.u; Then we can make it inherit from X like this by writing to __proto__: Y.prototype.__proto__ = X.prototype; While the same thing could be accomplished without ever writing to __proto__ with: Y.prototype = Object.create(X.prototype); Y.prototype.constructor = Y; In the latter case, it is necessary to set the constructor property of the prototype so that the correct constructor is called by the new Y statement, otherwise new Y will call the function X. If the programmer does want new Y to call X, it would be more properly done in Y's constructor with X.call(this, u)

你必须创建一个自定义的Object.create()函数。它解决了Crockfords的问题,也调用了init函数。

这是可行的:

var userBPrototype = {
    init: function(nameParam) {
        this.name = nameParam;
    },
    sayHello: function() {
        console.log('Hello '+ this.name);
    }
};


function UserB(name) {
    function F() {};
    F.prototype = userBPrototype;
    var f = new F;
    f.init(name);
    return f;
}

var bob = UserB('bob');
bob.sayHello();

这里UserB类似于Object。创造,但要适应我们的需要。

如果你愿意,也可以拨打:

var bob = new UserB('bob');