I'm trying to make two instances (constructorOne
and constructorTwo
) of a function variable called myObjectConstructor
. For some reason I get the same result back for both instances when I call getProperty
.
//this is one other way of creating a Constructor function
var myObjectConstructor = function(){
this.myProperty = '';
init = function(str) {
this.myProperty = str;
},
getProperty = function() {
return this.myProperty;
}
return {
init: function () {
return init.apply(self, arguments);
},
getProperty: function () {
return getProperty.apply(self, arguments);
}
}
}
//instantiate our Constructor
var constructorOne = new myObjectConstructor();
//change myProperty of the first instance
constructorOne.init('this is property one');
//instantiate a second instance of our Constructor
var constructorTwo = new myObjectConstructor();
constructorTwo.init('this is property two');
Both constructorOne.getProperty()
and constructorTwo.getProperty()
will alert "this is property two":
alert(constructorOne.getProperty()); //this will alert 'this is property two'
alert(constructorTwo.getProperty()); //this will still alert 'this is property two'
Here is a demo.
Question is, why does constructorOne.getProperty()
not return 'this is property one'?