javascript 切换上下文,事件绑定中改变this指向

在事件绑定中,调用回调函数时改变this的指向,通常有几种做法,原生的bind()方法,和jquery中的$.proxy()。如果在事件绑定中,想让上下文从目标html元素中切换为局部变量,就可以这样做。

两个例子:

func.bind(obj); 

参数:  func ,要调用的函数对象,必选

     obj ,this 关键字可在新函数中引用的对象,必选

返回:  与 func 函数相同的新函数

new function(){ 
    this.appName = "wem";
    document.documentElement.addEventListener("click", function(e){
            alert(this.appName);
        }.bind(this), false); 
};

 

var person = {
        name:"Kevin Yang",
        sayHi:function(){
            alert("你好,我是"+this.name);
        }
    }
var boundFunc = person.sayHi.bind(person);
setTimeout(boundFunc,5000);

 

$.proxy(func, this)

参数:  func ,要调用的已有函数对象,必选

     obj ,this 关键字可在新函数中引用的对象,必选

返回:  与 func 函数相同的新函数

new function(){
  this.appName = "wem2";
  document.documentElement.addEventListener("click", $.proxy(function(){
    alert(this.appName)
  } ,this), false);
};

 

posted @ 2015-11-19 16:58  otss  阅读(563)  评论(0编辑  收藏  举报