javascript:使用继承"照原样”;

javascript: using inheritance "as is"

本文关键字:quot 继承 javascript      更新时间:2023-09-26

我想在Javascript中使用一些非常简单的继承,而不需要任何库(jQuery、Prototype等),但我忘记了如何做到这一点。

我知道如何创建一个简单的非继承对象:

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原型,当调用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();  
    };  
}  

您可以使用此代码。它做的正是你所做的,这是我知道的唯一继承方式,但这个函数使用create,如果它可用的话,它在ECMAScritp5中是新的,并做一些额外的检查:

function inherit(p) {
if (p == null) throw TypeError(); // p must be non-null
if (Object.create) // If Object.create() is defined (ECMAScript 5 way)
return Object.create(p); // use it
var t = typeof p; // If not, do some more checking (the old way)
if (t !== "object" && t !== "function") throw TypeError();
function f() {}; // Define constructor
f.prototype = p; // Set prototype to p.
return new f(); // call constructor f() to create an "heir" of p
}