我有这样的代码:
var SEVERINU = SEVERINU || {};
SEVERINU.AutoGallery = {
galleryImagesNames: new Array(),
findImages: function () {
var dirToResearch = this.galleryName;
$.post(
"_php/get-files.php", {
dir: dirToResearch,
ext: this.fileExtension
}, function (data) {
var pliki = $.parseJSON(data);
console.log(data);
for (var i in pliki) {
this.galleryImagesNames.push(pliki[i]); // problem !
}
});
},
}
这一行:this.galleryImagesNames.push(pliki[i]);
给我带来了问题。
它说他找不到 var galleryImagesNames 等。
如果我要“深入”,如何调用函数、var?
最佳答案
只需将当前的 this
保存到其他变量,这样它就不会在函数内被覆盖。
var SEVERINU = SEVERINU || {};
SEVERINU.AutoGallery = {
galleryImagesNames : new Array(),
findImages : function(){
var self = this; // keep current value of this in variable named self
var dirToResearch = this.galleryName;
$.post(
"_php/get-files.php",
{
dir: dirToResearch,
ext: this.fileExtension
},
function(data){
var pliki = $.parseJSON(data);
console.log(data);
for(var i in pliki){
// call the method using self variable instead of this that got overwritten
self.galleryImagesNames.push(pliki[i]);
}
}
);
},
}
关于JavaScript 模块模式 : calling functions within nested function,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16594005/