JavaScript命名空间和继承

时间:2012-12-31 03:17:08

标签: javascript prototypal-inheritance

我在jsFiddle中有一些代码:http://jsfiddle.net/xyuY6/

代码:

var App= {};

App.WebPage = {
 WebPage : function(name) {
     alert("In Super");
     this.name = name;  
 },

 Home : function(name) {
      alert("In Sub");
      App.WebPage.WebPage.call(this, name);
 }


};

App.WebPage.WebPage.prototype.sayName = function() {
alert(this.name);
};

inherit(App.WebPage.WebPage, App.WebPage.Home);

var x = new App.WebPage.Home("zack");
x.sayName();

function inherit(subType, superType) {
    alert("IN HERE");
    var p = Object.create(superType);
    p.constructor = subType;
    subType.prototype = p;
}

我要做的是创建一个App命名空间,在此命名空间中有两个构造函数WebPageHomeWebPage是“超级类型”,Home是“子类型”。 Home应该从WebPage继承所有内容。

但问题是,正如您在运行JavaScript时所看到的那样,当我执行x.sayName时,WebPage原型上定义的sayName函数未被调用。因此,它不是遗传的。

为什么?

感谢您的帮助!!!

2 个答案:

答案 0 :(得分:2)

似乎你在某个时刻(在调用或inherit的定义中)混合了超类和子类......

以下是固定代码(如果我了解您要尝试的内容):http://jsfiddle.net/45uLT/

var App= {};

App.WebPage = {
     WebPage : function(name) {
         alert("In Super");
         this.name = name;  
     },

     Home : function(name) {
          alert("In Sub");
          App.WebPage.WebPage.call(this, name);
     }


};


App.WebPage.WebPage.prototype.sayName = function() {
    alert(this.name);
};

inherit(App.WebPage.WebPage, App.WebPage.Home);

var x = new App.WebPage.Home("zack");
x.sayName();

function inherit(superType, subType) {
    alert("IN HERE");
    var p = new superType;
    subType.prototype = p;
    subType.prototype.constructor = subType;
}

希望这是你想要的。

答案 1 :(得分:1)

以下是jsfiddle中的一个工作示例,基于您在上面尝试做的事情:

http://jsfiddle.net/8GwRd/

var App = (function() {
    function WebPage(name) {
        this.type = 'WebPage';
        this.name = name;
    }

    WebPage.prototype.sayName = function() {
      alert(this.name + ' is a ' + this.type);
    };

    function Home(name) {
        WebPage.call(this, name);
        this.type = 'Home'
    }

    Home.prototype = new WebPage();

    return {
        WebPage: WebPage,
        Home: Home
    };       

})();

var y = new App.WebPage('bob');
y.sayName();

var x = new App.Home("zack");
x.sayName();