PDA

View Full Version : Pure javascript question



kovtik
20 Oct 2006, 8:10 AM
Please look at this simple example:
ClassA = function(){
if (this.shouldAdd)
this.elems.push(111);
};
ClassA.prototype.shouldAdd = true;

ClassB = function(){
ClassB.superclass.constructor.call(this);
};
YAHOO.extendX(ClassB, ClassA);

ClassB.prototype.elems = [1, 2, 3];

var obj1 = new ClassB();//obj1.elems == [1, 2, 3, 111]
var obj2 = new ClassB();//obj2.elems == [1, 2, 3, 111, 111]
Why call to this.elems.push() modifies ClassB.prototype.elems? How can I solve this problem?

jack.slocum
20 Oct 2006, 8:36 AM
Object properties defined on the prototype are shared between all instances. Initialize the array in the contructor (this.elems = [1, 2, 3]) and the problem should go away.

kovtik
23 Oct 2006, 6:13 AM
Thank you for your previous answer. Now I have another question :)

YAHOO.ext library contains definition of the Date class, which overrides global predefined Date class. How can I access predefined Date class?

(I was faced with this when I wanted to parse string containing minutes and seconds in format without trailing zeros, like "5:2", but I didn't find correct format characters for minutes and seconds. However, during searching I tested the following call:
Date.parseDate("43:14", "i:s");The returned result had zeros in place of minutes and seconds. After that I decided to use global Date object, but I cannot access it)

jack.slocum
23 Oct 2006, 1:51 PM
The date code doesn't replace the default Date object, it only adds additional methods. For the standard Date parsing function, use Date.parse(). It doesn't support formats though.

I doubt parsing minutes and seconds only is ever going to work. I would recommend adding a default date and hour to the beginning of the string and then extracting the parsed minute/second values you need.