使用“Object.create”而不是“新” [英] Using "Object.create" instead of "new"

查看:218
本文介绍了使用“Object.create”而不是“新”的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Javascript 1.9.3 / ECMAScript 5介绍 Object.create ,其中Douglas Crockford等人主张很长一段时间。如何使用 Object.create

Javascript 1.9.3 / ECMAScript 5 introduces Object.create, which Douglas Crockford amongst others has been advocating for a long time. How do I replace new in the code below with 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)。

(Assume MY_GLOBAL.nextId exists).

最好的我可以想出是:

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?

There doesn't seem to be any advantage, so I think I'm not getting it. I'm probably being too neo-classical. How should I use Object.create to create user 'bob'?

推荐答案

只有一个级别的继承,您的示例可能不会让您看到 Object.create

With only one level of inheritance, your example may not let you see the real benefits of Object.create.

这种方法可以方便地实现差异继承,其中对象可以直接从其他对象继承。

This methods allows you to easily implement differential inheritance, where objects can directly inherit from other objects.

userB 不要认为你的 init 方法应该是public或甚至存在,如果你在现有的对象实例上再次调用这个方法, id <

On your userB example, I don't think that your init method should be public or even exist, if you call again this method on an existing object instance, the id and name properties will change.

Object.create

Object.create lets you initialize object properties using its second argument, e.g.:

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.create ,使用与 Object.defineProperties Object.defineProperty

As you can see, the properties can be initialized on the second argument of Object.create, with an object literal using a syntax similar to the used by the Object.defineProperties and Object.defineProperty methods.

它可以设置属性属性( enumerable writable 可配置),这是非常有用的。

It lets you set the property attributes (enumerable, writable, or configurable), which can be really useful.

这篇关于使用“Object.create”而不是“新”的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆