当前位置 : 首页 » 编程语言 » 正文

js绑定事件this指向发生改变的问题解决方法

分类 : 编程语言 | 发布时间 : 2018-04-21 09:06:21 | 浏览 : 0
可对函数进行如下扩展
复制代码 代码如下:

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)
}
}

复制代码 代码如下:

<P style="PADDING-BOTTOM: 0px; LINE-HEIGHT: 22px; MARGIN-TOP: 0px; FONT-FAMILY: 微软雅黑, 宋体, 'Trebuchet 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><P style="PADDING-BOTTOM: 0px; LINE-HEIGHT: 22px; MARGIN-TOP: 0px; FONT-FAMILY: 微软雅黑, 宋体, 'Trebuchet MS', Tahoma, Arial, sans-serif; MARGIN-BOTTOM: 10px; COLOR: rgb(34,34,34); FONT-SIZE: 14px; PADDING-TOP: 0px" class=p1>a.init();</P>

相关阅读:

How to move an element into another element?

Set HTTP header for one request

Remove duplicates from an array of objects in JavaScript

Can I call jquery click() to follow an <a> link if I haven't bound an event handler to it with bind or click already?

Check whether a string matches a regex in JS

jQuery event to trigger action when a div is made visible

Check if user is using IE with jQuery

Resize HTML5 canvas to fit window

How do I replace a character at a particular index in JavaScript?

JavaScript file upload size validation