将属性设置为类
问题描述:
我再有一个类MapFilter,它有条件地创建一个对象数组。将属性设置为类
创建类时,名为postCodeFilter
的属性会自动设置为null
。当使用类初始空值的逻辑正常工作:
MapFilter.prototype.filterByPostcode = function(res){
var newRes = [];
console.log(this.postcodeFilter);
if(typeof this.postcodeFilter !== 'undefined') {
for(var i = 0; i < res.length; i++) {
if(res[i].postcode == this.postCodeFilter) {
newRes.push(res[i]);
}
}
} else {
newRes = res.slice();
}
return newRes;
};
当开始运行调用此方法的方法,它将运行在所从事的其他块
无论其
设置为postcodeFilter
的值后,我不能再次将其设置为null
或undefined
。
我曾尝试以下方法,没有成功
delete this.serviceFilter;
this.serviceFilter = null;
this.serviceFilter = undefined;
我试图做的MapFilter
类的实例同样无济于事
如何重置一个类的属性再次是null
或undefined
?
答
function MapFilter(){
this.postcodeFilter=null
}
MapFilter.prototype.filterByPostcode = function(){
console.log(this.postcodeFilter);
if(this.postcodeFilter !== null) {
console.log('is bull')
} else {
console.log('is null')
}
}
var test = new MapFilter()
test.filterByPostcode()
test.postcodeFilter='bull'
test.filterByPostcode()
不使用type of null
不会返回null
,如果你调用原型内部功能
不要用this.postcodeFilter
尝试使用实例名称叫喜欢test.postcodeFilter
超出了试图删除/设置null serviceFilter属性的代码,你可以编辑你的帖子来包含使用/设置它的代码吗?或者您是否打算清除其他属性(例如'postcodeFilter')? –
请注意,对'typeof'进行'未定义'测试时,它不会捕获'null'值。 – Bergi
请提供[mcve]非工作代码。你提交的所有任务都应该按照你的意愿去做。 – Bergi