使用Object.create时如何设置单个私有变量

时间:2016-10-26 01:58:22

标签: javascript oop

我有一个原型函数,我用它来用Object.create()创建另外两个函数。但是,私有变量是共享的。如何让每个实例都有自己的变量实例?



var testCodePrototype = (function(){
  var score = 0;
  this.updateScore= function(amount){
    score += amount;
    return "Score updated to " + score;
  };
  this.getScore = function(){
    return score;
  };
  return {
    updateScore,
    getScore,
  };
}());
      
var test1 = Object.create(testCodePrototype, {
  name: {value: function(type){
  	return "I am test1";
  }}
});
var test2 = Object.create(testCodePrototype, {
  name: {value: function(type){
  	return "I am second.";
  }}
});

console.log(test1.name());
console.log(test2.name());
console.log(test1.updateScore(5));
console.log(test1.getScore()); // returns 5
console.log(test2.getScore()); // returns 5!!




2 个答案:

答案 0 :(得分:1)

您应该在每个对象中创建一个属性score,并将其与this限定符一起使用:

var testCodePrototype = (function(){

    this.updateScore= function(amount){
        this.score += amount;
        return "Score updated to " + this.score;
    };
    this.getScore = function(){
        return this.score;
    };
    return {
        updateScore,
        getScore
    };
}());

var test1 = Object.create(testCodePrototype, {
    name: {value: function(type){
        return "I am test1";
    }},
    score: {writable:true,value:0}
});

var test2 = Object.create(testCodePrototype, {
    name: {value: function(type){
        return "I am second";
    }},
    score: {writable:true,value:0}
});

console.log(test1.name());
console.log(test2.name());
console.log(test1.updateScore(5));
console.log(test1.getScore());  // 5
console.log(test2.getScore());  // 0

答案 1 :(得分:0)

因为JavaScript是一种原型语言,原型上的方法和值将与所有" child"对象,因为对象是活动对象(而不是类模板),并且它们在运行时链接。在您的情况下,您指定一个"私人"变量(在闭包中保存的变量)并从子实例更新该变量。您所看到的行为是设计性的。

在您的情况下,您无法真正做您想做的事情。原型功能无法访问"私有"继承树中的变量更高。你可以用" public"虽然this已分配给对象本身的变量。

一个选项是创建新对象,并基本上将方法重写为实例方法。你不想这样做是可以理解的。但是,您也可以使用功能更强大的方法,使用函数currying来实现结果。