0

我有以下方法:

DBConnection.prototype.successHandler = function(){
  console.log("DB_INFO: Schema created");
  for (k in this) console.log(k);
  this.setStatus(DB_STATUS_OK);
}

我在这样的事务中调用它:

DBConnection.prototype.createSchema = function(){
  try {
    this.c2db.transaction(
      function(tx){
        tx.executeSql('CREATE TABLE IF NOT EXISTS person(id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, name TEXT NOT NULL DEFAULT "");',
        [], this.nullDataHandler, this.errorHandler);
        tx.executeSql("INSERT INTO person(id, name) VALUES (NULL, 'miloud');",
          [], this.nullDataHandler, this.errorHandler);
      },
      this.errorHandler,
      this.successHandler
    );
  } catch(e){
    console.log("DB_ERROR: error during insert with message: " + e);
    return;
  }
}

问题是我得到:Uncaught TypeError: Object [object Window] has no method 'setStatus' 这清楚地表明我正在访问的不是DBConnection我在成功回调中使用的实例。怎么来的?this 在回调中指的是什么?有没有办法克服这个问题?

编辑

回调定义为:

DBConnection.prototype.errorHandler = function(errorMsg){
  console.log("DB_ERROR: error creating schema with msg " + errorMsg.message);
}
DBConnection.prototype.successHandler = function(){
  console.log("DB_INFO: Schema created");
  for (k in this) console.log(k);
  this.setStatus(DB_STATUS_OK);
}

而 setStatus 方法为

DBConnection.prototype.setStatus = function(str_status){
  localStorage.setItem(db_name, str_status);
}

谢谢!

4

1 回答 1

2

发生这种情况是因为this在 javascript 函数中,在调用时以点符号表示它之前的对象。但是 javascript 中的函数是一等值,可以在对象之外调用(或者实际上,对于完全不同的对象)。例如,如果obj是一个对象:

obj.myFunc = function() { console.log(this) };
obj.myFunc(); // <- Here this === obj
var freeFunc = obj.myFunc; // The function is just a value, we can pass it around
freeFunc(); // <- Now this === the top object (normally window)
            // Still the same function, but *how* it was called matters

您正在做的是将引用的函数传递给this.successHandler调用transaction,但该函数对您从中获取它的对象一无所知。当它被调用时,transaction它在没有对象的情况下执行,this只是变成window.

为了解决这个问题,您可以使用 javascript 具有闭包的事实并使用另一个匿名函数包装该函数:

DBConnection.prototype.createSchema = function(){
  try {

    var that = this;

    this.c2db.transaction(
      function(tx){
        tx.executeSql('CREATE TABLE IF NOT EXISTS person(id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, name TEXT NOT NULL DEFAULT "");',
        [], this.nullDataHandler, this.errorHandler);
        tx.executeSql("INSERT INTO person(id, name) VALUES (NULL, 'miloud');",
          [], this.nullDataHandler, this.errorHandler);
      },
      this.errorHandler,
      function() { that.successHandler(); }
    );
  } catch(e){
    console.log("DB_ERROR: error during insert with message: " + e);
    return;
  }
}

现在successHandler会用thatas调用,this和原来的一样this

这是一个常见的误解,this但网上也有很多解释,只是谷歌“javascript this”。

于 2012-07-13T15:42:06.793 回答