2013-03-04 2 views
0

Я пропустил это по возвращении на вызов AJAX. У меня естьОтсутствует это на новом операторе

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"); 

В возвращении succeedCB это окно не interar экземпляр

+0

К сожалению, в это просто аббревиатура меняю, название. Спасибо за головы ups – Agus

+0

Вместо этого вы должны построить 'interar.Remote'. –

+0

Почему в вашем образце кода есть interar.Remoter = 'и' interar.Remote/* no r * /. Prototype.init = '? Это в вашем исходном коде? Почему «новый interar» вместо «нового interar.Remoter»? –

ответ

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

1

Cache 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.

Смежные вопросы