Cli*_*ote 17 javascript oop scope
假设我有一个调用的javascript函数/类Foo,它有一个名为的属性bar.我希望在bar实例化类时提供值,例如:
var myFoo = new Foo(5);
Run Code Online (Sandbox Code Playgroud)
将设为myFoo.bar5.
如果我创建bar一个公共变量,那么这是有效的,例如:
function Foo(bar)
{
this.bar = bar;
}
Run Code Online (Sandbox Code Playgroud)
但是,如果我想将其设为私有,例如:
function Foo(bar)
{
var bar;
}
Run Code Online (Sandbox Code Playgroud)
那么我如何设置私有变量的值bar,使其可用于所有内部函数foo?
jfr*_*d00 53
关于javascript中私有和受保护访问的最佳教程之一是:http://javascript.crockford.com/private.html.
function Foo(a) {
var bar = a; // private instance data
this.getBar = function() {return(bar);} // methods with access to private variable
this.setBar = function(a) {bar = a;}
}
var x = new Foo(3);
var y = x.getBar(); // 3
x.setBar(12);
var z = x.bar; // not allowed (x has no public property named "bar")
Run Code Online (Sandbox Code Playgroud)
Dig*_*ane 23
您必须在构造函数中放置需要访问私有变量的所有函数:
function Foo(bar)
{
//bar is inside a closure now, only these functions can access it
this.setBar = function() {bar = 5;}
this.getBar = function() {return bar;}
//Other functions
}
var myFoo = new Foo(5);
myFoo.bar; //Undefined, cannot access variable closure
myFoo.getBar(); //Works, returns 5
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
27083 次 |
| 最近记录: |