這讓我瘋狂。
似乎無法設置AJAX內部的屬性值。
下面是我的代碼
function Captcha(userKey) {
var self = this;
this.key;
this.getCaptchaKey = function(userKey) {
$.post('/api/captcha/get-key',data, function(data, status,jqXHR) {
if(status) {
self.key = data.data.captchaKey;
}
},"json");
};
this.getCaptchaKey(userKey);
}
我設置「這個」作爲「自我」從AJAX調用內部參考。
然後當我console.log()這個對象本身在對象之外時,它告訴我這個值已經設置好了。
self.captcha = new Captcha(self.userKey);
self.captchaKey = self.captcha.key
console.log(self.captcha);
因此,'self.captcha'返回的對象具有從AJAX調用設置的'key'的正確值。
但是當我CONSOLE.LOG(self.captcha.key),它說「未定義」
我一直在谷歌上搜索無處不在,但找不到答案。
第二個街區是什麼?在我看來,self是一個不好的變量名,因爲self有一個意義。 https://developer.mozilla.org/en-US/docs/DOM/window.self – epascarello
就像epascarello說的,你需要用回調來處理它。即功能Captcha(userKey,callback){... if(status){callback(data.data.captchaKey); }然後做新的驗證碼(self.userKey,function(key){self.captchaKey = key}); –