Pau*_*aul 6 javascript closures
研究一个我发现以下构建的JavaScript库:
theMethod: function () {
var m1 = new SomeClass();
return function (theParameter) {
this.someMethod();
m1.methodCall(this.someField1);
this.someField2 = 'some value';
}
}()
Run Code Online (Sandbox Code Playgroud)
theMethod的调用方式如下:
c.theMethod(paramValue);
Run Code Online (Sandbox Code Playgroud)
作者想用这个宣言说什么?
为什么不使用这样的声明:
theMethod: function (theParameter) {
var m1 = new SomeClass();
this.someMethod();
m1.methodCall(this.someField1);
this.someField2 = 'some value';
}
Run Code Online (Sandbox Code Playgroud)
在函数外声明变量会使函数每次都使用同一个对象。
一个示例(为简单起见,使用整数而不是对象):
var c = {
theMethod: function () {
var m1 = 0;
return function (theParameter) {
m1++;
console.log( m1 );
}
}()
};
c.theMethod(); c.theMethod(); // output: 1 2
var d = {
theMethod: function () {
return function (theParameter) {
var m1 = 0;
m1++;
console.log( m1 );
}
}()
};
d.theMethod(); d.theMethod(); // output: 1 1
Run Code Online (Sandbox Code Playgroud)
自调用函数的工作原理如下:
var c = {
theMethod: function () {
var m1 = 0;
return function (theParameter) {
m1++;
console.log( m1 );
}
}()
};
Run Code Online (Sandbox Code Playgroud)
c创建对象时,自调用函数调用自身,theMethod现在等于该函数的返回值。在这种情况下,返回值是另一个函数。
c.theMethod = function( theParameter ) {
m1++;
console.log( m1 );
};
Run Code Online (Sandbox Code Playgroud)
该变量m1对函数可用,因为它在定义函数时在作用域内。
从现在开始,当您调用时,c.theMethod()您将始终执行从自调用函数返回的内部函数,该函数本身仅在声明对象时执行一次。
自调用函数就像任何函数一样工作。考虑:
var c = {
theMethod: parseInt( someVariable, 10 )
};
Run Code Online (Sandbox Code Playgroud)
您不会期望parseInt()每次使用c.theMethod变量时都执行。替换parseInt为原始函数中的匿名函数,这完全相同。
是为了封装。m1 对于其他方法以及可能使用该方法的地方的外部访问是隐藏的。Javascript 程序员通常不关心封装(但他们应该关心重要的脚本),因为您需要使用闭包,这会使类的设计变得复杂,并且如果实现不当会降低性能。这就是为什么在图书馆之外你看不到这种结构的原因。
另外,您的第二段代码也不等效。等效的东西是:
theMethod: function (theParameter) {
if (typeof this.prototype.__private__ === "undefined") {
this.prototype.__private__= {}
}
if (typeof this.__private__.m1 === "undefined") {
this.prototype.__private__.m1= new SomeClass();
}
this.someMethod();
this.__private__.m1.methodCall(this.someField1);
this.someField2 = 'some value';
}
Run Code Online (Sandbox Code Playgroud)
但 m1 在这里并不是真正的私有。
另请注意,在那段代码中,m1 仅对返回的函数可见,如果 theMethod 是类的成员,则该类的其他方法将无法看到 m1(使其与 Java 上的“private”关键字不同) )。还取决于你如何声明 theMethod m1 将是相当于“static”的java(m1是一个对象原型上的函数,它是静态的,如果它不在原型上,它就不是静态的)。
| 归档时间: |
|
| 查看次数: |
1328 次 |
| 最近记录: |