Skip to content

Instantly share code, notes, and snippets.

@Hyvi
Created November 15, 2011 09:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Hyvi/1366540 to your computer and use it in GitHub Desktop.
Save Hyvi/1366540 to your computer and use it in GitHub Desktop.
11.15对javascript this的理解,灾难源于这样的一段代码
/**
* 关于事件监听最佳实践  
* http://www.cnblogs.com/snowball/archive/2006/08/16/478531.html
*/
function associateObjWithEvent(obj, methodName){
return (function(e){
e = e||window.event;
// obj == DthmlObject , it's OK , but obj == new DthmlObject(),it's not
// what to do in new xxx(), #TODO
//for(i in obj.prototype) {
   //console.log(i);
     //}
return obj[methodName](e, this); // error !!!
// return obj.prototype[methodName](e,this); // 当这个函数复制给事件属性时,this在运行的时候才决定,为element.
});
}
function DhtmlObject(elementId){
var el = document.getElementById(elementId);
if(el){
//
//el.onclick = associateObjWithEvent(DhtmlObject, "doOnClick");
//el.onmouseover = associateObjWithEvent(DhtmlObject, "doMouseOver");
//el.onmouseout = associateObjWithEvent(DhtmlObject, "doMouseOut");
// should use new DthmlObject() , this === DthmlOjbect ,otherwise this === windows
el.onclick = associateObjWithEvent(this, "doOnClick");
el.onmouseover = associateObjWithEvent(this, "doMouseOver");
el.onmouseout = associateObjWithEvent(this, "doMouseOut");
}
}
DhtmlObject.prototype.doOnClick = function(event, element){
alert(element);
// doOnClick method body.
}
DhtmlObject.prototype.doMouseOver = function(event, element){
// doMouseOver method body.
}
DhtmlObject.prototype.doMouseOut = function(event, element){
// doMouseOut method body.
}
new DhtmlObject("filetitle");
//DhtmlObject("filetitle");
参考资料:
http://yehudakatz.com/2011/08/11/understanding-javascript-function-invocation-and-this/ 作者相当的N。另外也讲到了对bind,对ecma 5的理解。
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment