问题描述
我一直在阅读很多关于javascript中继承的文章。其中一些使用 new
,而其他人推荐 Object.Create
。我读的越多,我就越困惑,因为它似乎存在无穷无尽的变种来解决继承问题。
I've been reading a lot of articles about "inheritance" in javascript. Some of them uses new
while others recommends Object.Create
. The more I read, the more confused I get since it seems to exist an endless amount of variants to solve inheritance.
有人可以向我展示最受欢迎的方式(如果有的话,还是事实上的标准)?
Can someone be kind to show me the most accepted way (or defacto standard if there is one)?
(我希望有一个基础对象模型
我可以extend RestModel
或 LocalStorageModel
。)
(I want to have an base object Model
which I can extend RestModel
or LocalStorageModel
.)
推荐答案
简单:所有环境都不支持Object.create
,但可以使用 new
。除此之外,两者有不同的目标:只创建一个继承自其他对象的Object,而 还调用构造函数。使用适当的。
Simple: Object.create
is not supported in all environments, but can be shimmed with new
. Apart from that, the two have different aims: Object.create
just creates a Object inheriting from some other, while new
also invokes a constructor function. Use what is appropriate.
在您的情况下,您似乎希望 RestModel.prototype
继承自 Model.prototype
。 Object.create
(或其shim)是正确的方法,因为你不想a)创建一个新实例(实例化新模型
)和b)不想调用Model构造函数:
In your case you seem to want that RestModel.prototype
inherits from Model.prototype
. Object.create
(or its shim) is the correct way then, because you do not want to a) create a new instance (instantiate a new Model
) and b) don't want to call the Model constructor:
RestModel.prototype = Object.create(Model.prototype);
如果要在RestModels上调用Model构造函数,那与原型无关。使用或:
If you want to call the Model constructor on RestModels, that has nothing to do with prototypes. Use call()
or apply()
for that:
function RestModel() {
Model.call(this); // apply Model's constructor on the new object
...
}
这篇关于正确的javascript继承的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!