我想在没有任何库(jQuery、Prototype 等)的情况下在 Javascript 中使用一些非常简单的继承,但我忘记了如何执行此操作。
我知道如何创建一个简单的非继承对象:
function Foo(x)
{
this.x = x;
}
Foo.prototype = {
inc: function() { return this.x++; }
}
然后我可以按如下方式使用它:
js>f1=new Foo(0)
[object Object]
js>f1.inc()
0
js>f1.inc()
1
js>f1.inc()
2
但是我如何在不更改 Foo 类的情况下添加一个具有继承 Foo“inc”方法的附加方法的子类?
function Bar(x)
{
this.x = x;
}
Bar.prototype = new Foo();
Bar.prototype.pow = function(y) { return this.x+"^"+y+"="+Math.pow(this.x,y); }
这似乎是正确的,只是构造函数有点奇怪;我必须调用一次 Foo 构造函数来创建 Bar 原型(prototype),而当调用 Bar 的构造函数时,似乎无法调用 Foo 构造函数。
有什么建议吗?
最佳答案
诀窍是使用 Object.create而不是执行 new Foo()
。它还将创建一个继承自 Foo.prototype 但不调用 Foo 构造函数的新对象。
Bar.prototype = Object.create(Foo.prototype);
虽然 Object.create 可能未在旧版浏览器上定义,但如果需要,您可以自己定义它。 (以下代码来自MDN链接)
if (!Object.create) {
Object.create = function (o) {
if (arguments.length > 1) {
throw new Error('Object.create implementation only accepts the first parameter.');
//tbh, the second parameter is for stuff you dont need right now.
}
function F() {}
F.prototype = o;
return new F();
};
}
关于javascript:使用继承 "as is",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9828553/