gpt4 book ai didi

javascript - 在 javascript 对象中从哪里设置 self ?

转载 作者:行者123 更新时间:2023-11-29 10:46:23 24 4
gpt4 key购买 nike

我注意到在我的对象实例中,如果我有一个 jQuery 单击处理程序等,this 关键字会被覆盖,因此我必须设置一个 self 属性超出范围并访问它。

我的问题是:

  • 我应该在我的对象主体中还是在每个方法中设置 self。 是有区别吗?
  • 在这种情况下,self 是否指向实例而不是类?

谢谢!

var ExampleVM = function () {
var self1 = this;
this.toggleIsSlidedOut = function () {
var self2 = this;
this.$con.animate({
right: '+=' + posX + 'px'
}, 400, function () {
selfx.isSlidedOut(!this.isSlidedOut());
});
};
};

最佳答案

Should I set self, in the body of my object, or in each method. Is there a difference?

由于下面的评论阐明了这是关于 .animate() 回调的:( previous post )

self1self2 之间的区别主要是风格问题。使用 self1,您只需定义一次。但是,self2 将使声明更接近它的使用位置。

但是,无论哪种方式,只要您对两个方法调用都使用 self(或 self1 等),它就会起作用:

self.isSlidedOut(!self.isSlidedOut());

因为 this 将引用已设置动画的 Element

注意:如果焦点在 toggleIsSlidedOut 上,就像我第一次那样,那么它可能会有所不同。然后,这取决于您是否希望该方法有效地绑定(bind)到实例 (self1) 或能够与其他上下文交互 (self2)。


Does self in this case point to the instance and not the class?

它应该指向实例。在任何 function 中,this 很少会引用正在调用的 function

如果你需要一个引用,你可以使用它的名字任何持有它的属性:

this.toggleIsSlidedOut = function actualFunctionName() {
console.log(actualFunctionName); // function ...

// ...
};

不过,如果您碰巧忘记将 newExampleVM 一起使用,this 可以引用“global"对象(浏览器中的 window)或 undefined

关于javascript - 在 javascript 对象中从哪里设置 self ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18689871/

24 4 0
文章推荐: javascript - 获取对象 # 在 Ember 中没有方法 'map'