简体   繁体   English

访问原型中的“私有”变量

[英]Access “private” variables in prototype

Is it possible in JavaScript to create a private variable which can be accessed in prototype? 是否有可能在JavaScript中创建一个可以在原型中访问的私有变量? I tried the following which obviously doesn't work , because bar is only accessible from within Foo and not from within prototype. 我尝试了下面这显然不起作用 ,因为bar只能从Foo访问,而不是从原型中访问。

function Foo() {
    var bar = 'test';
}

Foo.prototype.baz = function() {
    console.log(bar);
};

I know I also cannot use this.bar = 'test' , because that would make the property public AFAIK. 我知道我也不能使用this.bar = 'test' ,因为那样会使属性公开 AFAIK。 How to make the bar variable private, but accessible by prototype? 如何使bar变量私有,但可以通过原型访问?

You can't - it's impossible to access a lexically scoped variable from outside that scope. 你不能 - 从该范围之外访问一个词法范围的变量是不可能的。

Prototype methods are (by definition) shared between all instances, and to do so must exist in their own scope. 原型方法(根据定义)在所有实例之间共享,并且这样做必须存在于它们自己的范围内。

Douglas Crockford's article Private Members in JavaScript provides some useful explanations, but no solution that meets your requirements. Douglas Crockford的文章私有成员在JavaScript中提供了一些有用的解释,但没有满足您要求的解决方案。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM