在此使用"this".在JavaScript中使我感到困惑 [英] The use of "this" is confusing me in JavaScript

查看:59
本文介绍了在此使用"this".在JavaScript中使我感到困惑的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用JavaScript令人困惑的事情之一是使用this

Working with the JavaScript one of the confusing thing is when using this

var x = {  
  ele : 'test',
  init : function(){ 
    alert(this.ele);
  }
}

但是,当处理多个对象(尤其是事件)时,this的上下文会发生变化,并且变得难以跟踪/理解.

However when dealing with multiple object and especially events context of this changes and becomes confusing to keep track/understand.

因此,如果有人有更好的意见/建议/想法/更好的做法,请分享.我也想知道使用this是否具有任何(性能)​​优势或什么?

So if anybody has better inputs/guidelines/thoughts/better practices, please share. Also I would like know if using this gives any (performance) advantage or what?

推荐答案

这与性能无关,它与访问对象特定实例的属性有关:-

It's not about performance, it's about accessing a property of a specific instance of an object:-

x.init()

如果您未在函数中使用this,则不会显示测试".

Would not display 'test' if you hadn't use this in the function.

上面的行实际上与:-

x.init.call(x);

执行该功能时,将call中使用的第一个参数分配给this.

the first paramater in the use of call is assigned to this when the function is executed.

现在考虑:-

var fn = x.init;  //Note no () so the function itself is assigned to the variable fn
fn();

现在,您在警报中什么也没有得到.这是因为上面是有效的:-

Now you get nothing in the alert. This because the above is effectively:-

fn.call(window);

在浏览器托管的Javascript中,window对象与全局对象同义.当某个函数被称为原始"函数时,this默认为全局对象.

In browser hosted Javascript the window object is synonymous with the global object. When a function is called "in the raw" then the this defaults to the global object.

经典错误是在做这样的事情:-

The classic error is doing something like this:-

var x = {
   ele: 'test';
   init: function(elem) { 
      elem.onclick = function() { alert(this.ele); }
   }
}
x.init(document.getElementById('myButton'));

但是,这不起作用,因为附加到onclick事件的函数是由浏览器使用以下代码调用的:-

However this doesn't work because the function attached to the onclick event is called by the browser using code like:-

onclick.call(theDOMElement)

因此函数运行时this并不是您认为的那样.

Hence when the function is running this isn't what you think it is.

对于这种情况,我通常的解决方法是:-

My usual solution to this situation is:-

var x = {
   ele: 'test';
   init: function(elem) {
      var self = this; 
      elem.onclick = function() { alert(self.ele); }
      elem = null;
   }
}
x.init(document.getElementById('myButton'));

请注意elem = null是IE内存泄漏的解决方法.

Note the elem = null is IE memory leak work-around.

这篇关于在此使用"this".在JavaScript中使我感到困惑的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆