为什么不't将该方法作为参数工作传递

Why doesn't passing that.method as a parameter work?

本文关键字:参数 工作 方法 为什么不      更新时间:2023-09-26

在一个表示请求的类中,我尝试用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);
};