对象内部的 JavaScript 闭包:什么别名应该有“this”?用于传递给匿名函数?
我们与我们的团队讨论下一步: 正确的名称应该有变量,该变量将是匿名函数中“this”的别名。简单的例子:
var SomeConstructor = function() {
this.someProperty = 'bingo';
this.someMethod = function() {
var myObjectAlias = this;
$('a').click(function() {
alert( myObjectAlias.someProperty );
});
}
}
所以我的问题是 - 什么正确的名称应该有变量“myObjectAlias”?或者您的代码中使用了什么?
We have discussion with our team about next:
What correct name should have variable which will be alias for "this" in anonymous function. Simple example:
var SomeConstructor = function() {
this.someProperty = 'bingo';
this.someMethod = function() {
var myObjectAlias = this;
$('a').click(function() {
alert( myObjectAlias.someProperty );
});
}
}
So my question is - What correct name should have variable "myObjectAlias"? Or what used in your code for example?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
您会看到很多代码示例。
这样做;其实没关系,你想要什么就什么。
You see a lot of in code samples.
To do that; it really doesn't matter, whatever you want.
在这些情况下,我倾向于使用
self
,或者明确地使用_self
,具有this
的含义,而无需冲突,让事情简单直观,至少对我来说是这样。例如:
这当然是一个偏好问题,但我所交谈过的大多数 JS 开发人员都认为这种命名风格非常直观,这并不是说大多数人都这么认为,但事实并非如此没关系吧?做对你的团队有用的事情:)
I tend to use
self
in these cases, or_self
to be explicit, has the meaning ofthis
without the conflicts, keeping things simple and intuitive, at least for me.For example:
It's all a matter of preference of course, but the majority of JS developers that I've talked to find this naming style pretty intuitive, that's not to say the overall majority does, but that doesn't matter does it? Do what works for your team :)
我认为有时使用有意义的名称是件好事,例如“表单”或“容器”或其他名称。简而言之,小代码块并不是什么大问题,但在表单或对话框的复杂初始化中,往往会出现几个不同的“有趣”对象。
I think sometimes it's good to use meaningful names, like "form" or "container" or whatever. In short little blocks of code is not that big a deal, but in complicated initializations for forms or dialogs there tends to be several different "interesting" objects buzzing around.
我更喜欢使用 self ,原因是 Nick Craver 描述的。
I prefer to use
self
for reasons Nick Craver described.切线:考虑为构造函数使用原型:
someProperty 和 someMethod 属性可以在所有实例之间共享,因此它们可以通过这种方式正常工作。每当您需要为每个实例提供单独的值时,您应该将它们放在构造函数本身中。
on a tangent: consider using prototypes for your constructor:
The someProperty and someMethod properties can be shared among all instances, so they work fine this way. Whenever you need separate values for each instance, you should put those in the constructor itself.