2016-10-26 4 views
3

Object.create()で2つの他の関数を作成するために使用するプロトタイプ関数があります。しかし、プライベート変数は共有されています。どのようにして各インスタンスに変数のインスタンスを持たせることができますか?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){ 
 
    \t return "I am test1"; 
 
    }} 
 
}); 
 
var test2 = Object.create(testCodePrototype, { 
 
    name: {value: function(type){ 
 
    \t 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!!

+0

あなたはコンストラクタ関数を必要としています。あるいは 'init'メソッドです。 – Bergi

+0

可能な複製[新規の代わりにObject.create()を使用してプライベートメンバーを持つオブジェクトを作成する方法](https://stackoverflow.com/q/11253717/1048572) – Bergi

答えて

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

+0

「this.score」も私的でも変数でもない。 – Bergi

0

JavaScriptはプロトタイプ言語であるので、オブジェクトはライブオブジェクト(ないクラステンプレート)であるため、プロトタイプのメソッドと値は、すべての「子」オブジェクトと共有され、それらは実行時にリンクされます。あなたのケースでは、 "プライベート"変数(クロージャ内に保持されている変数)を指定し、その変数を子インスタンスから更新しています。あなたが見ている動作は設計によるものです。

あなたの場合、実際にあなたがやろうとしていることをすることはできません。 Prototype関数は、継承ツリーの上位の "private"変数にアクセスすることはできません。 thisでも、オブジェクト自体に割り当てられた "public"変数でこれを行うことができます。

新しいオブジェクトを作成し、基本的にメソッドをインスタンスメソッドとして書き換えることもできます。あなたがそれをしたくないことは分かります。しかし、関数をカリングして結果を達成する、より機能的なアプローチを使用することもできます。

関連する問題