有没有办法制作"私有"变量(在构造函数中定义的变量),可用于原型定义的方法?
TestClass = function(){
var privateField = "hello";
this.nonProtoHello = function(){alert(privateField)};
};
TestClass.prototype.prototypeHello = function(){alert(privateField)};
Run Code Online (Sandbox Code Playgroud)
这有效:
t.nonProtoHello()
Run Code Online (Sandbox Code Playgroud)
但这不是:
t.prototypeHello()
Run Code Online (Sandbox Code Playgroud)
我习惯在构造函数中定义我的方法,但由于一些原因,我正在远离它.
好吧,我试图弄清楚这有可能以任何方式.这是代码:
a=function(text)
{
var b=text;
if (!arguments.callee.prototype.get)
arguments.callee.prototype.get=function()
{
return b;
}
else
alert('already created!');
}
var c=new a("test"); // creates prototype instance of getter
var d=new a("ojoj"); // alerts already created
alert(c.get()) // alerts test
alert(d.get()) // alerts test from context of creating prototype function :(
Run Code Online (Sandbox Code Playgroud)
如你所见,我试图创建原型getter.为了什么?好吧,如果你写这样的东西:
a=function(text)
{
var b=text;
this.getText=function(){ return b}
}
Run Code Online (Sandbox Code Playgroud)
......一切都应该没问题......但实际上每次创建对象时 - 我都会创建使用内存的getText函数.我想在记忆中有一个原型功能可以做同样的事情...任何想法?
编辑:
我试过Christoph给出的解决方案,它似乎是目前唯一已知的解决方案.它需要记住id信息以从上下文中检索值,但是整个想法对我来说很好:) Id只是要记住的一件事,其他一切都可以在内存中存储一次.实际上,您可以通过这种方式存储许多私有成员,并且只能使用一个id.实际上这让我很满意:)(除非有人有更好的主意).
someFunc = function()
{
var store = new Array();
var guid=0;
var someFunc = function(text)
{
this.__guid=guid;
store[guid++]=text; …Run Code Online (Sandbox Code Playgroud)