以class-extend.js样式扩展自定义对象

时间:2013-10-04 19:05:47

标签: inheritance javascript

我正在使用class-extend.js在我的JS代码中实现简单继承:

var Man = Class.extend({
    init: function(name) {
        this.name = name;
    }
});

var Mr = Man.extend({
    init: function(name) {
        this._super("Mr. " + name);
    }
});

var mrBean = new Mr("Bean");

JSFiddle

如何修改脚本以从没有class-extend.js实现的对象继承?

function AnotherMan(name) {
    this.name = name;
}

...
?

2 个答案:

答案 0 :(得分:2)

您可以在extend功能上使用.call()。这需要init原型方法指向构造函数:

function AnotherMan(name) {
    this.name = name;
}
AnotherMan.prototype.init = AnotherMan; // = AnotherMan.prototype.constructor;

var Mr = Class.extend.call(AnotherMan, {
    init: function(name) {
        this._super("Mr. " + name);
    }
});
var mrBean = new Mr("Bean");

updated demo

当然,使用原生Correct javascript inheritance而不是Class库可能会更容易......

function AnotherMan(name) {
    this.name = name;
}

function Mr(name) {
    AnotherMan.call(this, "Mr. " + name);
}
Mr.prototype = Object.create(AnotherMan.prototype, {
    constructor: {value: AnotherMan}
});

var mrBean = new Mr("Bean");

答案 1 :(得分:0)

以下内容将实现您的目标:(working jsFiddle)。它使用原型链来实现经典继承。

function AnotherMan(name) {
    this.name = name;
}

function Mr(name) {
    AnotherMan.call(this, name); // Call the superclass's constructor in the scope of this.
    this.name = "Mr. " + name; // Add an attribute to Author.
}

Mr.prototype = new AnotherMan(); // Set up the prototype chain.
Mr.prototype.constructor = Mr; // Set the constructor attribute to Mr.

var mrBean = new Mr("Bean");

您可以将其概括为一个函数:(Another Working jsFiddle

function extend(subClass, superClass) {
    var F = function() {};
    F.prototype = superClass.prototype;
    subClass.prototype = new F();
    subClass.prototype.constructor = subClass;

    subClass.superclass = superClass.prototype;
    if(superClass.prototype.constructor == Object.prototype.constructor) {
        superClass.prototype.constructor = superClass;
    }
}

并像这样使用它:

function AnotherMan(name) {
    this.name = name;
}

function Mr(name) {
    Mr.superclass.constructor.call(this, name);
    this.name = "Mr. " + name;
}
extend(Mr, AnotherMan);

var mrBean = new Mr("Bean");