解决js绑定事件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)

    }

}

var a  = new myalert();

a.init();


 

 


 

posted @ 2013-04-23 12:00  javawebsoa  Views(377)  Comments(0Edit  收藏  举报