为什么我的JavaScript实例返回相同的?

bri*_*nch 0 javascript oop

我正在尝试创建一个函数变量的两个实例(constructorOneconstructorTwo)myObjectConstructor.出于某种原因,当我打电话时,我得到两个实例的相同结果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');
Run Code Online (Sandbox Code Playgroud)

双方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'
Run Code Online (Sandbox Code Playgroud)

这是一个演示.

问题是,为什么不constructorOne.getProperty()归还'这是属性'?

Que*_*tin 6

selfundefined这样的初始化函数里面,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()); 
Run Code Online (Sandbox Code Playgroud)

要么

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());
Run Code Online (Sandbox Code Playgroud)