When I'm trying to create a new constructor object within another constructor function, I can't use this.time
when I create the object. But I can use this.time
in a method and return the value. How come it is like this?!
I only get undefined
in return when I run the second console.log. It's about this line: timeControl: new TimeControl(this.time)
If I use a value like 33
it works fine, but not with this.time
Interested and curious why the code act like this?
(To minimize the code in this question, I'm not showing the TimeControl
constructor)
// Box
Box = function(x,y,value) {
this.x = x;
this.y = y;
this.time = value;
// Create a new object of TimeControl
//this.timeControl = new TimeControl(this.time); // OK to create object here!
}
Box.prototype = {
// Create a new object of TimeControl
timeControl: new TimeControl(this.time), // But not OK here! Works if I enter a number
test1: function() {
return this.time;
},
test2: function() {
return this.timeControl.getTime();
}
};
var box = new Box(10,10,14);
console.log("Duration: " + box.test1()); // Works fine
console.log("Duration: " + box.test2()); // Returns undefined if this.time is used