我想为我自己的对象进行设置,女巫可以在附加时识别相同的对象并丢弃它们。
function ImageSet(){
this.set = [];
}
ImageSet.prototype.length = function(){return this.set.length}
ImageSet.prototype.process = function(imgObj){
var is_exist = false;
$.each(this.set, function(i){
if (this.set[i].imgHash == imgObj.imgHash){is_exist = true};
});
if (!is_exist){
this.set[this.set.length + 1] = imgObj;
return true;
}
return undefined;
}
var imagesChoosen = new ImageSet();
因此,当用户单击元素时,我创建新对象并尝试将其附加到我的图像集中。 第一次单击对象成功附加到集合,但第二次单击控制台写入错误
TypeError: this.set is undefined if (this.set[i].imgHash == imgObj.imgHash){is_exist = true};
调用ImageSet的代码是:
$('#content_table a').click(function(event){
event.preventDefault();
el = new Image($(this).attr('href'));
if (imagesChoosen.process(el)){
$(this).parent().css("border", "3px dotted orange");
} else {
$(this).parent().css("border", "None");
}
console.log(imagesChoosen.length());
return false;
});
我听不懂。我的 ImageSet 在第一次调用后是否被破坏?
最佳答案
在您传递给 each
的匿名函数内:
$.each(this.set, function(i){
if (this.set[i].imgHash == imgObj.imgHash){is_exist = true};
});
…this
的值是当前正在操作的数组的成员,而不是 imagesChoosen
。
要访问它,您需要将 this
从外部函数复制到保留在作用域内的另一个变量。
var is_exist = false;
var currentImageSet = this;
$.each(this.set, function(i){
if (currentImageSet.set[i].imgHash == imgObj.imgHash){is_exist = true};
});
关于javascript - 为什么类的属性丢失了?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13551862/