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

来源:互联网 发布:摄影师修图软件 编辑:程序博客网 时间:2024/05/29 16:40

可对函数进行如下扩展

 

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

var a  = new myalert();

a.init();