![]() |
|
|
|||||||
![]() |
|
|
Thread Tools | Rate Thread |
|
|
PM User | #1 |
|
New to the CF scene Join Date: Dec 2009
Posts: 2
Thanks: 0
Thanked 0 Times in 0 Posts
![]() |
Setting id attribute in subclass
Hello!
I have a superclass where I create a "div" element as a property and then proceed to try and set the element's "id" attribute in a subclass. Interestingly, if I create multiple instances of the subclass with different "id"s, they all end up having the last "id" I specify. I would like it if they retain the individual "id" I specify. Here is the code. Code:
function Drag() {
this.ele = document.createElement("div"); }
function Icon(id) {
this.ele.id = id; }
Icon.prototype = new Drag();
var hello = new Icon("hello");
var goodbye = new Icon("goodbye");
Last edited by willat8; 12-21-2009 at 06:33 AM.. Reason: Thought I'd discovered something, but it turned out I hadn't |
|
|
|
|
|
PM User | #2 |
|
New to the CF scene Join Date: Dec 2009
Posts: 2
Thanks: 0
Thanked 0 Times in 0 Posts
![]() |
For the purposes of what I am trying to do, I've solved it.
I think the issue was that when "Icon" asked for "this.ele", it always received the same object, as the "ele" property was defined in "Drag" once, not every time a new instance of "Icon" was created. Making changes to this same object meant that all instances of "Icon" reflected these changes. My solution is to call a method in "Icon" which creates a new "this.ele" for use by the current instance. Code:
function Drag() {
this.createNew = function() {
this.ele = document.createElement("div"); } }
function Icon(id) {
this.createNew();
this.ele.id = id; }
Icon.prototype = new Drag();
var hello = new Icon("hello");
var goodbye = new Icon("goodbye");
|
|
|
|
|
|
PM User | #3 |
|
Moderator ![]() ![]() Join Date: Jun 2007
Location: USA
Posts: 523
Thanks: 25
Thanked 74 Times in 72 Posts
![]() |
The reason it didn't work is because all Icon instances (as you have it) use the same prototype (a single Drag object). Thus when you change the prototype, the changes get shared amongst all objects that share the same prototype. But you have the right track in your second post. But there is a better and cleaner way.
This is what you want to do: Code:
function Drag() {
this.ele = document.createElement("div");
}
function Icon(id) {
For more info on Function.prototype.call: https://developer.mozilla.org/en/Cor.../Function/call
__________________
Trinithis Last edited by Trinithis; 12-21-2009 at 07:19 AM.. |
|
|
|
![]() |
| Bookmarks |
| Tags |
| class, inheritance, prototype |
| Thread Tools | |
| Rate This Thread | |
|
|