javascript:使用继承 "as is"

标签 javascript oop inheritance

我想在没有任何库(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/

相关文章:

c# - 从简单方法中删除重复代码 - 做得太过分了吗?

C++ - 将两个子类的共同成员

c# - 为什么不能 List<parent> = List<child>?

javascript - 如何在服务器端使用D3js直接生成SVG?

javascript - 在 Internet Explorer 中单击按钮后检查运行哪个 JavaScript 函数

php - 使用 PHP 类型将嵌套对象序列化/反序列化为 JSON

c++ - 派生类错误 'no type named my_data in <base class>'

javascript - 如何在 Backbone.js 的 View 中获取模型属性?

javascript - 如何重置使用 edit-json-file 编辑的文件

php - 使用php删除数据