This question already has answers here:
How to access the correct `this` inside a callback?
                                
                                    (10个回答)
                                
                        
                5年前关闭。
            
        

当使用JavaScript字符串替换为可选函数参数时,它将丢失类对象。该jsfiddle包含以下代码,可以最好地证明该问题。请注意,Person对象的“ orig_last_name”永远不会更新,因为replace函数不适用于Person对象。有没有办法将类传递给replace函数,还是有更好的办法?

该示例很简单,所以我知道有一种解决示例问题的简便方法,但是我的实际应用程序需要使用大字符串,查找要替换的模式,然后通过检查要替换的当前字符串来动态修改类对象。最后一部分是我遇到的问题。

function Person() {
  this.full_name = "Bruce Wayne";
  this.last_name = null;
  this.orig_last_name = null;
}

Person.prototype.updateLastName = function() {
  // "this" is the Person object.
  console.log("in updateLastName()", this);
  this.last_name = this.full_name.replace(/\s+\S+$/g, this._replace_last_name);
}

Person.prototype._replace_last_name = function(s) {
  // "this" is now the Window object.
  console.log("in _replace_last_name()", this);
  this.orig_last_name = s;
  this.last_name = " Banner";
  return this.last_name;
}

var p1 = new Person();
p1.updateLastName();
console.log(p1.full_name, p1.last_name, p1.orig_last_name);

最佳答案

当您将方法作为回调传递时,不会传递与特定对象的关联。您可以使用.bind()解决创建临时存根函数的问题,该临时存根函数将作为.replace()回调函数传递,并且该存根函数将使该方法与您的对象重新统一,如下所示:

Person.prototype.updateLastName = function() {
  // "this" is the Person object.
  console.log("in updateLastName()", this);
  this.last_name = this.full_name.replace(/\s+\S+$/g, this._replace_last_name.bind(this));
}


工作演示:http://jsfiddle.net/jfriend00/ZYsA9/

10-07 19:10
查看更多