为什么将`this`分配给`self`并运行`self.method()`? [英] Why assign `this` to `self` and run `self.method()`?

查看:66
本文介绍了为什么将`this`分配给`self`并运行`self.method()`?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在阅读猫鼬中的来源

Collection.prototype.onOpen = function () {
  var self = this;
  this.buffer = false;
  self.doQueue();
};

我不明白为什么作者指定这个 self 并运行 self.doQueue()。为什么不运行:

I don't understand why the author assigns this to self and runs self.doQueue(). Why not just run:

this.buffer = false;
this.doQueue();

我是javascript的新手,感谢您的帮助。

I'm new to javascript, thanks for help.

推荐答案

你是对的,在这种情况下,他们可以简单地使用这个

You're right, in this instance they could have simply used this.

使用 me self 有点确保正确无误使用这个的上下文,因为在JavaScript中,这个的范围是变体。例如,如果你的类中有一个事件触发一个函数,这个会不同,并且不会是你的函数所包含的对象,而是调用的对象功能。要解决这个问题,人们经常使用 me self 来确保他们引用正确的对象... this ,与实际对象一样。

The use of me or self is a bit of a hack to ensure the correct context of this is used, as within JavaScript the scope of this is variant. If for example you have an event trigger a function within your class, this would be different, and wouldn't be your object that houses the function, but instead the object that called the function. To resolve this people often use me or self to ensure they're referring to the correct object... this, as in the actual object.

这篇关于为什么将`this`分配给`self`并运行`self.method()`?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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