为什么不't将该方法作为参数工作传递
Why doesn't passing that.method as a parameter work?
在一个表示请求的类中,我尝试用Q promise处理它,然后用两个简单的处理程序来发送处理结果。为什么这不起作用:
Request.prototype.process = function() {
var that = this;
return that.getParameter('method')
.then(function(method) {
// ... Some processing
})
.then(that.replyOK)
.fail(that.replyError);
};
但这确实是:
Request.prototype.process = function() {
var that = this;
return that.getParameter('method')
.then(function(method) {
// ... Some processing
})
.then(function(error) {
that.replyOK(error);
})
.fail(function(error) {
that.replyError(error);
});
};
JavaScript的作用域主要是词法。这意味着在:
function foo(){
var that = this;
//...
}
在foo that
的下面几行中,访问它的变量被设置为您所期望的。如果您在其他地方传递带有局部定义的函数,that
将不会在其词法(变量)环境中被捕获。
JavaScript还有动态this
,方法的this
由当前调用的对象决定。例如:
var a = {
x:3,
getX:function(){ return this.x; }
};
var b = {x:5};
b.getX = a.getX;
b.getX(); // returns 5
a.getX(); // returns 3
a.getX.call(b); // set `this` explicitly with .call, returns 5
var x = a.getX;
x(); // global x or undefined.
使用Function.prototype.bind
固定this
是可能的:
Request.prototype.process = function() {
return this.getParameter('method')
.then(function(method) {
// ... Some processing
})
.then(this.replyOK.bind(this))
.fail(this.replyError.bind(this));
};
或者,在EcmaScript 6语法中(节点中还不可用,但很快就会可用):
Request.prototype.process = () => { // arrow functions have lexical `this`
return that.getParameter('method')
.then(function(method) {
// ... Some processing
})
.then(this.replyOK)
.fail(this.replyError);
};
相关文章:
- 无法使我的文本参数与我的查询一起工作
- 如何使参数在事件函数中工作
- 将图标作为参数传递不会;t工作-谷歌地图
- 添加第二个参数时,Javascript函数将停止工作
- 当名称空间在id参数之前声明时,Angular UI路由器停止工作
- 窗口clearInterval()在没有参数的情况下工作
- 无法获取用户 ID 路由参数以在反应路由器中继上工作
- 在 .before() 中多次使用相同的参数并不像我预期的那样工作
- JS .replace(str, str):如何获取参数 1 中的变量并全局工作
- 忽略服务工作进程请求中的查询参数
- JQuery 函数突然停止工作,转换 Javascript 参数时出错
- 猫鼬对象 ID 不作为函数中的参数工作
- JavaScript onclick 函数在参数为整数而不是字符串时工作
- 添加参数时调用javascript函数停止工作,这真的不大声吗
- 缺少参数 &&&||括号中的运算符,但仍在工作
- g:message 在 Javascript / jQuery 中带有参数的参数无法按预期工作
- JSON.stringify()工作不正常-第二个参数消失
- 为什么Selenium WebDriver不使用JavaScript等待时间参数工作
- 如何使Javascript定时器为变量参数工作
- 为什么不't将该方法作为参数工作传递