如何更新对象内的 JavaScript this 指针以指向另一个对象?
我在使用 JavaScript 以及将一个函数作为另一个函数的参数传递时遇到了一些问题。
假设我们在一个类中,并执行类似的操作:
this.get('target').update(this.onSuccess, this.onFail);
- “目标”是一个 JavaScript 对象,它有一个名为 update() 的方法,
- 我正在调用此方法,并将调用者类的两个方法作为
更新中 的参数传递-method 有些事情发生了,当它完成时,该方法应该调用 onSuccess 方法或 onFail 方法。这看起来像:
update: function(onSuccess, onFail) {
if(true) {
onSuccess();
} else {
onFail();
}
}
到目前为止,一切都运行得很好!但是在调用者类(调用上面更新方法的那个)中定义的那些成功/失败方法中,我使用了一个 this 指针:
onFail: function() {
alert('Error: ' + this.get('target').error);
}
这个指针会导致一些问题。它并不指向最初定义该方法的类,而是指向“目标”对象。
我现在需要做的是在“目标”类内的 onSuccess / onFail 调用之前更新 this 指针,以使这些方法再次工作。但这不起作用,因为“左侧分配无效”错误。
对于这样的场景,最佳实践是什么?有什么想法吗?提前谢谢!
干杯
I'm having some trouble with JavaScript and the passing of a function as parameter of another function.
let's say we are inside a class and do something like that:
this.get('target').update(this.onSuccess, this.onFail);
- 'target' is a JavaScript-object that has a method called update()
- I'm calling this method and pass tow methods of the caller-class along as parameters
inside that update-method some stuff happens and when it's done that method should either call the onSuccess-method or the onFail-method. this looks something like:
update: function(onSuccess, onFail) {
if(true) {
onSuccess();
} else {
onFail();
}
}
until now, everything works pretty fine! but inside those success/fail-methods, that are defined in the caller-class (the one that calls above update-method), I'm using a this-pointer:
onFail: function() {
alert('Error: ' + this.get('target').error);
}
that this-pointer causes some issues. it doesn't point to the class where the method initially was defined but to the 'target'-object.
what I need to do now is to update the this-pointer right before the onSuccess / onFail calls inside the 'target'-class to make the methods work again. but this doesn't work due to a 'invalid assignment left-hand side'-error.
what is the best practice for a scenario like that? any ideas? thx in advance!!!
cheers
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
调用
update()
时有两种选择:call()
apply()
主要区别在于如何将参数传递给它。但它们都允许范围/上下文注入。
您的代码应该如下所示:
You have two options when calling
update()
:call()
apply()
the main difference being how you pass parameters to it. But they both allow scope/context injection.
Your code should look something like this:
您可以创建一个函数,将函数“绑定”到某个对象(使用闭包),然后将这些绑定函数传递给处理程序:
You can create a function that "binds" a function to a certain object (using a closure) and than pass these bound functions to the handler:
要重定向此,您需要在
Function
类中使用bind()
(或类似的)方法,几乎所有 JavaScript 库中都可以找到该方法:现在执行如下操作
:解释如下: JavaScript 中的绑定范围
To redirect this, you need a
bind()
(or similar) method in theFunction
class, as found in almost all JavaScript libraries:Now do something like this:
The mechanism is explained here: Binding Scope in JavaScript