OO JavaScript调用父方法

Sto*_*out 5 javascript oop

我一直试图掌握OO JavaScript并创建了一个简单的例子.

function BasePage(name) {
    this.init(name);
}

BasePage.prototype = {
    init: function(name) {
       this.name = name; 
    },
    getName: function() {
        return this.name;
    }
}

function FaqPage (name, faq) {
    this.init(name, faq);
}

FaqPage.prototype = new BasePage();

FaqPage.prototype = {
    init: function(name, faq) {
        BasePage.prototype.init.call(this, name);
        this.faq = faq; 
    },
    getFaq: function() {
        return this.faq;
    }
}

var faqPage = new FaqPage('Faq Page', 'Faq');

var text = faqPage.getName() + ' ' + faqPage.getFaq();
$('body').text(text);
Run Code Online (Sandbox Code Playgroud)

运行此结果会导致以下消息:

未捕获TypeError:对象#<Object>没有方法'getName'

我想知道的是如何getName()在超类中调用该方法而不必在子类中重写和调用它?

如果我认为这种做法不好/好的话.

Dan*_*Dan 6

发生该错误是因为即使您将FaqPage原型设置为实例BasePage,您的下一行也会立即覆盖它.所以FaqPage不是继承自BasePage.将属性/方法添加到FaqPage原型中,而不是第二次定义它:

FaqPage.prototype.init = function(name, faq) {
    BasePage.prototype.init.call(this, name);
    this.faq = faq; 
}
FaqPage.prototype.getFaq = function() {
    return this.faq;
}
Run Code Online (Sandbox Code Playgroud)


Aad*_*hah 1

我感受到你的痛苦。正如其他人提到的getName,是undefined因为您覆盖了prototypeof FaqPage。因此我不会重复这个解释。

话虽这么说,我确实同意将prototype方法封装在单个范围内是很好的。也许您应该使用 JavaScript 库来实现此目的。最小的一个是augment。事实上它只有 17 行长:

Function.prototype.augment = function (body) {
    var base = this.prototype;
    var prototype = Object.create(base);
    body.apply(prototype, Array.from(arguments, 1).concat(base));
    if (!Object.ownPropertyOf(prototype, "constructor")) return prototype;
    var constructor = prototype.constructor;
    constructor.prototype = prototype;
    return constructor;
};

(function funct() {
    var bind = funct.bind;
    var bindable = Function.bindable = bind.bind(bind);
    var callable = Function.callable = bindable(funct.call);
    Object.ownPropertyOf = callable(funct.hasOwnProperty);
    Array.from = callable([].slice);
}());
Run Code Online (Sandbox Code Playgroud)

如果您使用的话,您的代码将如下所示augment

var BasePage = Object.augment(function () {
    this.constructor = function (name) {
        this.name = name;
    };

    this.getName = function () {
        return this.name;
    };
});

var FaqPage = BasePage.augment(function (base) {
    this.constructor = function (name, faq) {
        base.constructor.call(this, name);
        this.faq = faq;
    };

    this.getFaq = function () {
        return this.faq;
    };
});
Run Code Online (Sandbox Code Playgroud)

然后您可以像平常一样使用它:

var faqPage = new FaqPage("Faq Page", "Faq");
var text = faqPage.getName() + " " + faqPage.getFaq();
$("body").text(text);
Run Code Online (Sandbox Code Playgroud)

希望有帮助。