简体   繁体   中英

Access “private” variables in prototype

Is it possible in JavaScript to create a private variable which can be accessed in prototype? I tried the following which obviously doesn't work , because bar is only accessible from within Foo and not from within prototype.

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. How to make the bar variable private, but accessible by prototype?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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