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

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

问题描述

Javascript 1.9.3/ECMAScript 5 引入了 Object.create,Douglas Crockford 和其他人已经 倡导 已久.如何将下面代码中的 new 替换为 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 存在).

我能想到的最好的方法是:

The best I can come up with is:

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 方法不应该是公开的,甚至不应该存在,如果您在现有对象实例上再次调用此方法,idname 属性会改变.

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.definePropertiesObject.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.

它允许您设置属性属性(enumerablewritableconfigurable),这非常有用.

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

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

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