Reputation: 1994
I have some code in jsFiddle here: http://jsfiddle.net/xyuY6/
And the code:
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;
}
What I'm trying to do is create a App
namespace with two constructors in this namespace, WebPage
and Home
. WebPage
is a "super type" and Home
is the "sub type". Home should inherit everything from WebPage.
The problem though, as you'll see when you run the JavaScript, is the sayName function defined on the WebPage prototype is not being called when I do x.sayName
. Thus, it's not being inherited.
Why?
Thanks for the help!!!
Upvotes: 1
Views: 378
Reputation: 13809
Here's a working example in jsfiddle based on what you're trying to do above:
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();
Upvotes: 1
Reputation: 5094
It seems like you got the superclass and subclass mixed up at some point (either in the call or in inherit
's definition)...
Here's the fixed code (if I understand what you are trying to do): 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;
}
Hope this is what you wanted.
Upvotes: 2