js绑定事件this指向发生改变的问题解决方法
js绑定事件this指向发生改变的问题解决方法
发布时间:2016-12-30 来源:查字典编辑
摘要:可对函数进行如下扩展复制代码代码如下:Function.prototype.bind=function(obj){var_this=this...

可对函数进行如下扩展

复制代码 代码如下:

Function.prototype.bind = function(obj) {

var _this = this;

return function() {

_this.apply(obj,arguments);

}

}

用法如下

复制代码 代码如下:

var a = function(){

alert(this.title)

}.bind(document);

a();

常用在这儿

复制代码 代码如下:

function myalert() {

this.title = 'hello world';

this.init = function() {

$("#xxx").click(this.close.bind(this));

}

this.close = function() {

alert(this.title)

}

}

复制代码 代码如下:

<PTrebuchet MS', Tahoma, Arial, sans-serif; MARGIN-BOTTOM: 10px; COLOR: rgb(34,34,34); FONT-SIZE: 14px; PADDING-TOP: 0px" class=p1>var a = new myalert();</P><PTrebuchet MS', Tahoma, Arial, sans-serif; MARGIN-BOTTOM: 10px; COLOR: rgb(34,34,34); FONT-SIZE: 14px; PADDING-TOP: 0px" class=p1>a.init();</P>

推荐文章
猜你喜欢
附近的人在看
推荐阅读
拓展阅读
相关阅读
网友关注
最新Javascript教程学习
热门Javascript教程学习
编程开发子分类