有什么理由在 JavaScript 中使用 Object.create() 或 new 吗?

发布于 2024-11-18 17:10:53 字数 254 浏览 4 评论 0原文

到目前为止,我一直在 JavaScript 中使用 new 关键字。我一直在阅读有关 Object.create 的内容,我想知道是否应该使用它。我不太明白的是,我经常需要运行构造代码,因此我根本不知道 Object.create 将如何工作,因为它不会触发任何函数运行。

谁能告诉我,在什么情况下我应该使用Object.create而不是new

I've been using the new keyword in JavaScript so far. I have been reading about Object.create and I wonder if I should use it instead. What I don't quite get is that I often need to run construction code, so I don't see how Object.create is going to work at all since it does not trigger any functions to run.

Could anyone tell me, In which case should I use Object.create instead of new?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

み零 2024-11-25 17:10:53

到目前为止,如果要创建对象,只能使用字面量:

var obj = {};

Object构造函数。

var obj = Object();

但这些方法都不允许您指定所创建对象的原型

这就是您现在可以使用 Object.create 执行的操作。它允许您创建一个新对象并将第一个参数设置为新对象的原型。此外,它还允许您设置作为第二个参数提供的新对象的属性。

它类似于执行这样的操作(没有第二个参数):

function create(proto) {
    var Constr = function(){};
    Constr.prototype = proto;
    return new Constr();
}

因此,如果您使用与此类似的构造,则当您想要使用Object.create时。

它不能替代new。它更多的是使创建应该从另一个对象继承的单个对象更简单。

示例:

我有一个对象 a:

var a = {
   someFunction: function() {}
};

并且我希望 b 扩展该对象。然后你可以使用Object.create

b = Object.create(a);
b.someOtherFunction = function(){};

只要你有一个构造函数,但你只从中实例化一个对象,你就可以将其替换为Object .创建

有适用的一般规则。这在很大程度上取决于构造函数正在做什么以及如何从其他对象继承等。

So far, if you want to create an object, you can only use literals:

var obj = {};

or the Object constructor.

var obj = Object();

But none of these methods let you specify the prototype of the created object.

This is what you can do with Object.create now. It lets you create a new object and sets the first argument as prototype of the new object. In addition, it allows you to set properties of the new object provided as second argument.

It is similar to doing something like this (without the second argument):

function create(proto) {
    var Constr = function(){};
    Constr.prototype = proto;
    return new Constr();
}

So if you are using a construct similar to this, this when you wanted to use Object.create.

It is not a replacement for new. It is more an addition to make creating single objects which should inherit from another object simpler.

Example:

I have an object a:

var a = {
   someFunction: function() {}
};

and I want b to extend this object. Then you can use Object.create:

b = Object.create(a);
b.someOtherFunction = function(){};

Whenever you have a constructor function, but you only instantiate one object from it, you might be able to replace this with Object.create.

There is general rule that applies. It depends very much on what the constructor function is doing and how you inherit from other objects, etc.

哭泣的笑容 2024-11-25 17:10:53

正如已经提到的,当您想要一种简单的方法来设置新对象的原型时,通常会使用Object.create()。但其他答案没有提到的是,构造函数(需要 new)与任何其他函数并没有什么不同。

事实上,任何函数都可以返回一个对象,在 JavaScript 中很常见工厂函数(比如构造函数,但它们不需要 new,或者使用 this 来引用)到新对象)。工厂函数经常使用Object.create()来设置新对象的原型。

var barPrototype = {
  open: function open() { /* ... */ },
  close: function close() { /* ... */ },
};
function createBar() {
  return Object.create(barPrototype);
}

var bar = createBar();

As already mentioned, Object.create() is commonly used when you want an easy way to set the prototype of a new object. What the other answers fail to mention though, is that constructor functions (which require new) are not all that different from any other function.

In fact, any function can return an object, and it's common in JavaScript to see factory functions (like constructors, but they don't require new, or use this to refer to the new object). Factory functions often use Object.create() to set the prototype of the new object.

var barPrototype = {
  open: function open() { /* ... */ },
  close: function close() { /* ... */ },
};
function createBar() {
  return Object.create(barPrototype);
}

var bar = createBar();
离去的眼神 2024-11-25 17:10:53

超级晚了这个线程..但我认为需要做出的一个重要区别是,虽然构造函数只是函数,但 new 运算符调用该函数并捕获结果对象,这在动态环境中可能有用。它也允许在构造函数执行期间引用属性和方法,这可能有用也可能没用,具体取决于情况。如果您更关心拥有一个固定的原型,但对象本身更静态,则 Object.create 将是一个更好的选择,因为它更干净,并且不会像 new 运算符那样以意想不到的方式扰乱原型链。

一些简单的例子..

var Foo = function(element) {
  this.elem = element;
  $(this.elem).css('color', 'blue');
  // using the new operator here gives access to this.elem
  // immediately after that declaration is made, thus providing 
  // a comfortable dynamic system to work with 
}

var bar = new Foo(someElem);

相对于..

var foo = {
  elem : element,             // assume elem exists
  $(this.elem).css('color', 'blue')// in the lexical scope
}

var bar = Object.create(foo);
// This.elem does not exist until the object is returned now
// and the .css method call will not execute

应该稍微清楚为什么你想使用一个而不是另一个,作为另一个简单的细分...

当你关心拥有一个动态对象而不是原型链时使用

New当您不太关心动态而更关心拥有显式原型链时,使用 Object.create 。我还要指出的是,使用 Object.create 创建的对象也可以通过使用名为 init 的方法动态构建,您可以构建该方法以根据您的需要分配属性,然后只需在新返回的对象上调用它即可。

每种方法都有其优点和缺点,但在我看来,它们的用例相当不同。但是,您很可能会发现自己正在使用 Object.create,因为大多数情况都需要不太动态的情况并且更需要继承。

Super late to this thread.. but I think an important distinction that needs to be made is that while constructors are just functions, the new operator invokes the function and captures the resulting object which can be useful when in a dynamic environment. It allows reference to properties and methods during execution of the constructor as well which may or may not be useful depending on the situation. If you are more concerned with having a set prototype but the object itself is more static than not, Object.create would be a better option as it is cleaner and doesn't mess with the proto-chain in unexpected ways as the new operator does.

some simple examples..

var Foo = function(element) {
  this.elem = element;
  $(this.elem).css('color', 'blue');
  // using the new operator here gives access to this.elem
  // immediately after that declaration is made, thus providing 
  // a comfortable dynamic system to work with 
}

var bar = new Foo(someElem);

as apposed to..

var foo = {
  elem : element,             // assume elem exists
  $(this.elem).css('color', 'blue')// in the lexical scope
}

var bar = Object.create(foo);
// This.elem does not exist until the object is returned now
// and the .css method call will not execute

It should be slightly clearer why you would want to use one over the other, as another simple breakdown...

Use New when you care about having a dynamic object and less about the prototype chain

Use Object.create when you care less about being dynamic and more about having an explicit prototype chain. I will also note that objects made with Object.create can be dynamically built as well by using a method called init that you can build to assign properties based on your needs and simply call it on your freshly returned object.

Each approach has it's ups and downs however their use cases are fairly distinct in my opinion. However, you will most likely find yourself using Object.create as most situations will call for a less dynamic situation and have more need for inheritance.

盛装女皇 2024-11-25 17:10:53

Object.create() 函数的确切源代码是:

function Object.Create(proto, propertiesObject)
{
    var obj = {};

    Object.setPrototypeOf(obj, proto);

    if(propertiesObject)
    {
        Object.defineProperties(obj, propertiesObject);
    }

    return obj;
}

The exact source code for the Object.create() function is:

function Object.Create(proto, propertiesObject)
{
    var obj = {};

    Object.setPrototypeOf(obj, proto);

    if(propertiesObject)
    {
        Object.defineProperties(obj, propertiesObject);
    }

    return obj;
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文