有什么理由在JavaScript中使用Object.create()或new吗? [英] Is there any reason to use Object.create() or new in JavaScript?
问题描述
到目前为止,我一直在JavaScript中使用 new
关键字。我一直在阅读 Object.create
,我想知道是否应该使用它。我不太了解的是,我经常需要运行构造代码,因此我看不到 Object.create
怎么工作,因为它没有作用触发任何要运行的功能。
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.
任何人都可以告诉我,在这种情况下,我应该使用 Object.create
而不是 new
?
Could anyone tell me, In which case should I use Object.create
instead of new
?
推荐答案
到目前为止,如果要创建对象,则只能使用文字:
So far, if you want to create an object, you can only use literals:
var obj = {};
或 Object
构造函数。
var obj = Object();
但是这些方法都不能让您指定所创建对象的 prototype
But none of these methods let you specify the prototype of the created object.
这就是您现在可以使用 Object.create
进行的操作。它使您可以创建一个新对象,并将第一个参数设置为新对象的原型。另外,它允许您设置作为第二个参数提供的新对象的属性。
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();
}
因此,如果您使用与此类似的结构,则在需要使用 Object.create
。
So if you are using a construct similar to this, this when you wanted to use Object.create
.
它不能替代 new
。
示例:
我有一个对象 a
:
var a = {
someFunction: function() {}
};
,我希望 b
扩展此对象。然后可以使用 Object.create
:
and I want b
to extend this object. Then you can use Object.create
:
b = Object.create(a);
b.someOtherFunction = function(){};
每当您具有构造函数时,您仅实例化一个对象它,您可以用 Object.create
替换它。
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.
这篇关于有什么理由在JavaScript中使用Object.create()或new吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!