0

我在这里有一个基类:

function Screen(src) {
this.src = src;
}

Screen.prototype.html = function(collapsed) {
    return $.ajax({
        async : false,
        url : this.src + "?collapsed=" + collapsed,
    }).responseText;
};

然后我尝试对它进行子类化:

function TitleScreen() {
    Screen.call(this, "title.php");
};
TitleScreen.prototype = Object.create(Screen.prototype);
TitleScreen.prototype.constructor = TitleScreen;
TitleScreen.prototype.parent = Screen.prototype;

但是,当我这样做并尝试使用 TitleScreen 对象时,它设置了 src 属性,但未定义 html 函数!我还尝试在构造函数中设置 html 函数,如下所示:

function Screen(src) {
    this.src = src;
    this.html = function(collapsed) {
        return $.ajax({
            async : false,
            url : this.src + "?collapsed=" + collapsed,
        }).responseText;
    };
}

但这也没有用。我做错了什么可能导致普通的旧属性起作用但不起作用?

4

2 回答 2

0

忘记new关键字了吗?只有当你创建了构造函数的实例时,对象才会从prototype对象继承:

var title = new TitleScreen();
"html" in title; // true

jsfiddle.net 上的演示

或者您是否有一些您没有向我们展示的附加代码覆盖TitleScreen.prototype而不是向其添加属性?

于 2012-10-17T13:36:44.840 回答
0

我的问题实际上与继承完全无关;它与本地存储有关。

调用 new TitleScreen().html() 实际上确实返回了 HTML,但我将 Screen 对象序列化为 JSON 并将它们放在本地存储中,以便我的应用程序可以记住它的状态。然而,序列化显然没有考虑到这些功能,所以我失去了这些。

为了解决我的问题,当我从本地存储反序列化时,我需要重新构造函数。

于 2012-10-17T14:05:24.173 回答