在Javascript中实现私有实例变量 [英] Implementing private instance variables in Javascript
问题描述
我不知道我多久都错过了这个。我一直假设私有实例变量像这样工作,但他们没有。当然,它们是私有的(如非全局的),但变量是跨实例共享的。这导致了一些非常令人困惑的错误。
I don't know how I've missed this for so long. I've been presuming private instance variables to work like this, but they don't. They're private (as in non-global), certainly, but the variables are shared across instances. This led to some very confusing bugs.
我认为我正在遵循一些最好的库实现的最佳实践,但似乎我错过了一些东西。
I thought I was following the best practices implemented by some of the best libraries out there, but it seems I missed something.
var Printer = (function(){
var _word;
Printer = function(word){
_word = word;
}
_print = function(){
console.log(_word);
}
Printer.prototype = {
print: _print
}
return Printer;
})();
var a = new Printer("Alex");
var b = new Printer("Bob");
a.print(); //Prints Bob (!)
b.print(); //Prints Bob
我看过这篇文章,但它没有描述最佳实践实现私有实例变量。 (这甚至是我想要的名字吗?)
JavaScript中私有变量和实例变量的方法和变量范围
I have looked at this post, but it doesn't describe a best practice for implementing private instance variables. (is this even the name of what I want?) Method and variable scoping of private and instance variables in JavaScript
我也查看了这篇文章,但是使用'this '关键字是我以前做的。因为它没有混淆我试图避免它。这真的是唯一的方法吗?
在原型继承中实现实例方法/变量
I also looked at this post, but the use of the 'this' keyword is what I used to do. Because it doesn't obfuscate I was trying to avoid it. Is this really the only way? Implementing instance methods/variables in prototypal inheritance
推荐答案
你正在做那个关闭的好东西。 _word
需要在 Printer
函数中声明,而不是在匿名封闭的土地中丢失:
You're doing some wonky stuff with that closure. _word
needs to be declared in the Printer
function, not lost in anonymous-closure land:
function Printer(word) {
var _word = word;
this.print = function () {
console.log(_word);
}
}
var a = new Printer("Alex");
var b = new Printer("Bob");
a.print(); //Prints Alex
b.print(); //Prints Bob
这保持 _word
private ,代价是在每个 Printer
实例上创建一个新的 print
函数。要降低此成本,您需要公开 _word
并在原型上使用单个 print
函数:
This keeps _word
private, at the expense of creating a new print
function on every Printer
instance. To cut this cost, you expose _word
and use a single print
function on the prototype:
function Printer(word) {
this._word = word;
}
Printer.prototype.print = function () {
console.log(this._word);
}
var a = new Printer("Alex");
var b = new Printer("Bob");
a.print(); //Prints Alex
b.print(); //Prints Bob
真的 是否重要 _word
是否已曝光?就个人而言,我不这么认为,特别是考虑到 _
前缀。
Does it really matter that _word
is exposed? Personally, I don't think so, especially given the _
prefix.
这篇关于在Javascript中实现私有实例变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!