访问“私人”原型中的变量 [英] Access "private" variables in prototype

查看:74
本文介绍了访问“私人”原型中的变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在JavaScript中是否可以创建可在原型中访问的私有变量?我尝试了以下显然不起作用,因为 bar 只能访问来自 Foo ,而不是来自原型。

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);
};

我知道我也不能使用 this.bar ='test',因为这会使公共财产公开 AFAIK。如何将 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的文章 JavaScript中的私人会员 提供了一些有用的解释,但没有符合您要求的解决方案。

Douglas Crockford's article Private Members in JavaScript provides some useful explanations, but no solution that meets your requirements.

这篇关于访问“私人”原型中的变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆