码迷,mamicode.com
首页 > 编程语言 > 详细

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

时间:2015-11-19 18:38:25      阅读:159      评论:0      收藏:0      [点我收藏+]

标签:

在事件绑定中,调用回调函数时改变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); 
};

 

$.proxy(func, this)

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

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

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

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

 

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

标签:

原文地址:http://www.cnblogs.com/otss/p/4978176.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!