更新时间:2022-05-29 01:50:46
是的,恐怕不是如何设置层次结构。它接近,但有几个关键问题。 (其中一个<—调用 new Mammal()
创建 Cat.prototype
— ,
Yes, I'm afraid that's not how you set up hierarchies. It's close, but there are a couple of key issues. (One of which — calling new Mammal()
to create Cat.prototype
— is a very, very, very frequent error you see in a lot of blog posts and such.)
这是一个简单的例子:
// A function to set up the link between a child and parent
function derive(Child, Parent) {
// `ctor` is a temporary function we use so we can get an object
// backed by `Parent.prototype` but without calling `Parent`.
function ctor() { }
// Borrow the prototype
ctor.prototype = Parent.prototype;
// Create an object backed by `Parent.prototype` and use it as
// `Child`'s prototype
Child.prototype = new ctor();
// Some housekeeping to make the prototype look like the ones
// the JavaScript engine creates normally.
Child.prototype.constructor = Child;
// Note: If we can rely on ES5 features, we could use
// `Object.create` instead of the `ctor` function.
}
// The parent constructor
var Mammal = function(name) {
this.name = name;
};
// Some stuff for its prototype
Mammal.prototype.get_name = function() {
return this.name;
};
Mammal.prototype.says = function () {
return this.saying || '';
};
// The child constructor
var Cat = function(name) {
Mammal.call(this, name);
this.saying = "Meow";
};
// Hook it up to the parent
derive(Cat, Mammal);
// Add some things to its prototype
Cat.prototype.purr = function (number) {
var i =0, s='';
for ( i=0; i<number; i++)
if (s)
s +='-';
s+='r';
return s;
};
如果你有兴趣在JavaScript中做继承层次结构,你可能会发现我的 沿袭
脚本有用。你可能或可能不会选择使用它,但它演示了如何设置的东西,一种方法来调用父的版本的方法(supercalls)等。特别是,本文档网页使用沿袭
比较不使用它显示如何没有任何帮助脚本这样做。但是有一个原因我写了一个帮助脚本来做。 : - )
If you're interested in doing inheritance hierarchies in JavaScript, you may find my Lineage
script useful. You may or may not choose to use it, but it demonstrates how to set things up, a way to do calls to the parent's version of methods ("supercalls"), etc. In particular, this documentation page comparing using Lineage
to not using it shows how to do this without any helper script. But there's a reason I wrote a helper script to do it. :-)