San*_*der 2 javascript this prototypejs
我有一个带命名空间的Javascript函数,我使用Prototype来执行一个函数.示例代码:
GUI.Title = {
initialise: function() {
var elements = $$('a');
this.show(); /* now it refers to the namespace */
elements.each(function(element) {
this.show(); /* this refers to the window object, not to the namespace */
});
},
show: function() {
element.show();
}
}
Run Code Online (Sandbox Code Playgroud)
'this'指的是每个函数外部的命名空间,每个函数内部都指向窗口.
有人可以向我解释我如何在每个循环中使用'this'作为名称空间的引用者?
我正在使用Prototype.
Nic*_*ick 11
使用Prototype的bind方法修改this函数内部的含义.
elements.each(function(element) {
this.show();
}.bind(this));
Run Code Online (Sandbox Code Playgroud)
更换
this.show(); /* now it refers to the namespace */
elements.each(function(element) {
this.show(); /* this refers to the window object, not to the namespace */
});
Run Code Online (Sandbox Code Playgroud)
同
var scope = this;
elements.each(function(element) {
scope.show(); /* this refers to the window object, not to the namespace */
});
Run Code Online (Sandbox Code Playgroud)
你正在做的是创建一个闭包,'scope'var以词法方式"封闭"到你的每个函数.请注意,此方法不是原型特定的,它是一种通用的JavaScript技术.
| 归档时间: |
|
| 查看次数: |
160 次 |
| 最近记录: |