Nic*_*rdu 3 javascript oop jquery
通常(如果不总是),当jQuery允许您向某些JS事件添加回调(如click)时,在回调函数中,它们会更改this触发事件的DOM元素的"含义" .
这可能非常有用,但是当你在js中编写OOP代码时,它会阻碍你,就像在这个例子中一样:
function MyClass() {}
MyClass.prototype = {
init: function() {
$("#someSpan").click(this.doSomething);
},
doSomething: function() {
alert("Here 1");
this.test();
return false;
},
test: function() {
alert("Here 2");
}
}
Run Code Online (Sandbox Code Playgroud)
在这个例子中,this.test()将不起作用,因为this它不再是一个实例,MyClass而是一个jQuery DOM元素(span).
我的问题是:有没有办法继续使用这种模式在JS中编写OOP代码并使用jQuery?并且:为什么jQuery会this在回调函数中发生变化,因为它可以轻松地将jQuery DOM元素作为第一个参数发送?
jQuery $.proxy可以像这样使用:
function MyClass() {
this.clicked = $.proxy(this.clicked, this);
}
MyClass.prototype = {
clicked: function(e) {
alert("Here 1");
this.test();
e.currentTarget; //this replaces "this"-the keyword used in "non OOP" contexts
//see http://api.jquery.com/event.currentTarget/
},
init: function() {
$("#someSpan").click(this.clicked);
},
test: function() {
alert("Here 2");
}
}
Run Code Online (Sandbox Code Playgroud)
创建实例时,该实例会获得自己的.clicked函数,该函数会隐藏原型中的通用函数.this无论你怎么称呼它都会有相同的绑定.所以你可以通过this.clicked各地,让它工作.
| 归档时间: |
|
| 查看次数: |
398 次 |
| 最近记录: |