I'm kinda new to OOJS so please bear with me on this. I'm trying to get a setup like the following:
Item
name = "no name"
description = "no description"
someVar = "no var"
Section
name = "Section A"
//Rest are inherited
deleted = false
So far I have:
function Item() {}
function Section() {}
$.extend(Item.prototype, {
name: "no name",
description: "no description"
}
Section.prototype = Item.prototype;
$.extend(this.Section.prototype, {
description: "A section",
swung: true,
swing: function() {
this.swung = false;
return this;
}
});
$.extend(this.Item.prototype, {
"date": "x"
});
$.extend(this.Section.prototype, {
"someVar": "someValue"
});
If I create a new Section, I get:
Section {
name: "no name",
description: "A section",
swung: true,
swing: function,
date: "x",
someVar: "someValue"
}
If I create a new Item, I get:
Item {
name: "no name",
description: "A section",
swung: true,
swing: function,
date: "x",
someVar: "someValue"
}
Obviously they're both the same, and the reason is that the prototype is the same instance. What I am trying to achieve is that all functions which inherit from Item pick up properties whenver they're added, and any changes to the value of a property on the Item prototype do not affect the property on Section if it has been overridden beforehand. Any changes to the Section prototype should not affect the Item prototype (as has obviously happened above) as there will be properties specific to Section. Does anyone know of any way to achieve this?
If I'm not being clear, please say so rather than downvoting me :). Thanks in advance.
1 Answer 1
When inheriting in JS, you don't assign one prototype to another. Instead, you assign an instance of the parent to the child's prototype:
Section.prototype = new Item();
You can check out a simplified version of your code (without the need for jQuery, which just unnecessarily complicates everything): http://jsfiddle.net/p3h5C/
1 Comment
Explore related questions
See similar questions with these tags.
Item.prototype.date = "x";Item.prototype. .... I'm just experimenting now - when it comes to applying it at work, I'll write it the long way.