2014-12-22 4 views
0

Я пытаюсь сделать два экземпляра (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() не возвращает 'это свойство'?

+0

Потому что вы ссылаетесь на 'this' в обоих объектах, которые были перезаписаны в момент инициализации второго объекта. – SaschaM78

+0

Потому что 'self' не определен, поэтому' getProperty' вызывается в контексте 'окна' оба раза. –

+0

Как использовать функции и прототип конструктора объясняется здесь: http://stackoverflow.com/a/16063711/1641941 надеюсь, что это поможет. – HMR

ответ

6

self является undefined так внутри функции инициализации, this является window, так что вы всегда изменение свойств одного и того же объекта.

Вы, кажется, делаете какой-то странный гибрид шаблона модуля и стандартных функций JavaScript-конструктора. Я настоятельно рекомендую выбрать один из двух подходов и придерживаться его.

function MyObjectConstructor(){ 
 
    this.myProperty = ''; 
 
} 
 

 
MyObjectConstructor.prototype.init = function(str) { 
 
     this.myProperty = str; 
 
}; 
 
MyObjectConstructor.prototype.getProperty = function() { 
 
     return this.myProperty; 
 
}; 
 
    
 
//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'); 
 

 
//alert current myProperty of constructorOne instance 
 
alert(constructorOne.getProperty()); 
 

 
//alert current myProperty of constructorTwo instance 
 
alert(constructorTwo.getProperty());

или

function myModule(){ 
 
    var myProperty = ''; 
 
    return { 
 
    init: function (str) { 
 
     myProperty = str; 
 
    }, 
 
    getProperty: function() { 
 
     return myProperty; 
 
    } 
 
    }; 
 
} 
 

 
//instantiate our Constructor 
 
var constructorOne = myModule(); 
 
    
 
//change myProperty of the first instance 
 
constructorOne.init('this is property one'); 
 
    
 
//instantiate a second instance of our Constructor 
 
var constructorTwo = myModule(); 
 
    
 
constructorTwo.init('this is property two'); 
 

 
//alert current myProperty of constructorOne instance 
 
alert(constructorOne.getProperty()); 
 

 
//alert current myProperty of constructorTwo instance 
 
alert(constructorTwo.getProperty());

+0

Дангит, ниндзя. –

+0

Если я использую ваш первый вариант (с прототипом) и имею функции в моем объекте, которые должны звонить друг другу, как бы я это сделал? Скажем, у меня есть эти две функции: MyObjectConstructor.prototype.func1 = функция (НТР) {} MyObjectConstructor.prototype.func2 = функция (НТР) { как позвонить func1 отсюда? } – brinch

+0

Вы продолжаете получать ссылку на объект с помощью 'this':' this.func1() ' – Quentin

1

Лучший способ сделать это будет использовать собственные прототипы:

function MyObjectConstructor() { 
    this.property = ''; 
} 

MyObjectConstructor.prototype.init = function(newProperty) { 
    this.property = newProperty; 
}; 

MyObjectConstructor.prototype.getProperty = function() { 
    return this.property; 
}; 
Смежные вопросы