Я пытаюсь сделать два экземпляра (constructorOne
и constructorTwo
) функциональной переменной с именем myObjectConstructor
. По какой-то причине я получаю тот же результат для обоих экземпляров, когда я вызываю getProperty
.Почему мои экземпляры JavaScript возвращают то же самое?
//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');
Оба constructorOne.getProperty()
и constructorTwo.getProperty()
предупредит "это свойство два":
alert(constructorOne.getProperty()); //this will alert 'this is property two'
alert(constructorTwo.getProperty()); //this will still alert 'this is property two'
Вот demo.
Вопрос, почему constructorOne.getProperty()
не возвращает 'это свойство'?
Потому что вы ссылаетесь на 'this' в обоих объектах, которые были перезаписаны в момент инициализации второго объекта. – SaschaM78
Потому что 'self' не определен, поэтому' getProperty' вызывается в контексте 'окна' оба раза. –
Как использовать функции и прототип конструктора объясняется здесь: http://stackoverflow.com/a/16063711/1641941 надеюсь, что это поможет. – HMR