使用“Object.create”而不是“New”

使用“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();

(假设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.create创建用户‘bob’?


慕桂英4014372
浏览 287回答 3
3回答

慕少森

使用Object.create(...)过关new object.提倡这种方法的人通常说出相当模糊的优点:“可伸缩性”,或“JavaScript更自然“等等。然而,我还没有看到一个具体的例子,表明Object.create有任何优于使用new..相反,它存在已知的问题。SamElsamman描述了当存在嵌套对象和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(...)提倡这样一种做法数据用于创建新对象;Animal基准成为lion和bird,并造成问题,因为它是共享的。当使用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(...).
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript