帮助,“这个”让我在JavaScript中感到困惑 [英] Help, "this" is confusing me in JavaScript

查看:116
本文介绍了帮助,“这个”让我在JavaScript中感到困惑的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用JavaScript的一个令人困惑的事情是使用这个

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

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

但是当处理多个对象,特别是事件上下文时更改并变得令人困惑,无法跟踪/理解。

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

因此,如果有人有更好的输入/指引/想法/更好的做法,请分享。另外我想知道如果使用这个给出任何(性能)​​优势或什么?

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

如果你没有使用,则不会显示'test'函数中的此

实际上,上述行与以下行相同: -

Effectively the above line is the same as:-

x.init.call(x);

使用电话的第一个参数执行该函数时,

现在考虑: -

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中,窗口对象是与全局对象同义。当一个函数被称为原始时,那么这个默认为全局对象。

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)

因此当函数运行时,这个不是你想象的那样。

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.

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

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