0

AJAX 呼び出しの戻り時に this がありません。私が持っています

interar.js

interar.Remoter = function (data) {
  this.server = data.server;
  this.init(data);
};

interar.Remoter.prototype.init = function (data) {
    var succeedCB, errorCB, lPayload, promiseCB;
    succeedCB = function (result) {
        // When return the called the this is === window not in.
        this.uuid = result.uuid;
        console.log("UUID v4 From Server " +  this.uuid);
    };
    errorCB = function () {
        console.error("Not Allow to Connect to Server ");
    }
    // This execute a XHTTPRequest Async call
    interar.execute(succeedCB, errorCB, {'w' : data});
};

index.html

var W = new interar.Remoter("mydata");

successCBの戻り時、これはインスタンス間のウィンドウではありませ

4

2 に答える 2

1

thisインスタンスの初期化時にキャッシュ:

interar.Remoter.prototype.init = function (data) {
    var succeedCB, errorCB, lPayload, promiseCB, self = this;
    succeedCB = function (result) {
        // When return the called the this is === window not in.
        self.uuid = result.uuid;
        console.log("UUID v4 From Server " +  self.uuid);
    };
    errorCB = function () {
        console.error("Not Allow to Connect to Server ");
    }
    // This execute a XHTTPRequest Async call
    interar.execute(succeedCB, errorCB, {'w' : data});
};

prototype.initまた、おそらくのRemoter代わりにを設定したかったでしょうRemote

于 2013-03-04T13:47:18.950 に答える
0

そのはず

interar.Remote.prototype.init = function (data) {
    var succeedCB, errorCB, lPayload, promiseCB;
    var self = this; <-- Assign this to a variable for closure bases access
    succeedCB = function (result) {
        // When return the called the this is === window not in.
        self.uuid = result.uuid;
        console.log("UUID v4 From Server " +  self.uuid);
    };
    errorCB = function () {
        console.error("Not Allow to Connect to Server ");
    }
    // This execute a XHTTPRequest Async call
    interar.execute(succeedCB, errorCB, {'w' : data});
};

コールバックとして渡すsucceedCBと、実行元のコンテキストはインスタンスsucceedCBを認識しません。this

そのため、クロージャーを利用しthisて内部にアクセスできるようにすることができますsucceedCB

于 2013-03-04T13:47:34.070 に答える