function MyObject(element) { | |
this.elm = element; | |
element.addEventListener('click', this.onClick.bind(this), false); | |
}; | |
MyObject.prototype.onClick = function(e) { | |
var t=this; //do something with [t]... | |
//without bind the context of this function wouldn't be a MyObject | |
//instance as you would normally expect. | |
}; |
![]() |
1
superbear 2014-06-11 16:34:25 +08:00 ![]() 看不懂可以把this存到一个变量里例如,var _this = this。
|
![]() |
2
lijsh 2014-06-11 16:38:30 +08:00 ![]() 两个this都是同一个对象,就是以new调用MyObject时返回的实例对象。
添加事件处理函数时,当前作用域会丢失(即this会指向全局对象),因此这里要把this.onClick绑定回当前的this中。 还有一种会丢失作用域的情况是定时函数,所以如果想保存原来的上下文,同样需要为定时函数添加this绑定。 |
![]() |
3
exoticknight 2014-06-11 16:55:21 +08:00 ![]() 很多时候主要是代码运行的环境不一样导致this的指向变了,比如onclick执行的时候不是在你代码运行的时候而是你点击的时候。
|
![]() |
6
lijsh 2014-06-11 18:21:55 +08:00
@superbear 一般this会丢失的情况就几种,闭包里,还有就是事件处理函数和定时函数,其他情况下不怎么需要保存这个this
|
![]() |
7
pepsin 2014-06-11 18:29:29 +08:00
尽量避免用
|
![]() |
8
mcfog 2014-06-11 19:06:27 +08:00
|