コードはここで遊ぶことができます - http://jsfiddle.net/dsjbirch/zgweW/14/
これは基本的に、クロックフォードのプライベート変数の説明をそのままコピーして貼り付けたものです。
Object.create()
少しトレースを追加しました。
2 番目のオブジェクトが最初のオブジェクトのプライベート メンバーを共有するのはなぜですか? この状況を回避しながら使用を続けるにはどうすればよいですかObject.create()
function Container(param) {
function dec() {
if (secret > 0) {
secret -= 1;
return true;
} else {
return false;
}
}
this.member = param;
var secret = 3;
var that = this;
this.service = function () {
return dec() ? that.member : null;
};
}
var first = new Container("private");
var second = Object.create(first);
document.write(first.service() + "<br/>");
document.write(first.service() + "<br/>");
document.write(first.service() + "<br/>");
document.write(first.service() + "<br/>");
document.write(second.service() + "<br/>");
document.write(second.service() + "<br/>");
document.write(second.service() + "<br/>");
document.write(second.service() + "<br/>");
http://jsfiddle.net/dsjbirch/zgweW/14/
私は見ることを期待します
private
private
private
null
private
private
private
null
しかし、実際には 2 番目のオブジェクトの出力はすべて null です。
private
private
private
null
null
null
null
null
そのため、オブジェクトのメンバーsecond
を共有していると結論付けています。first
secret