js检测是否为某个对象公有、私有属性的方法
2018-07-25 本文已影响41人
world_7735
function Fn() {
//a和b是实例的私有属性
this.a = 100;
this.b = function () {
console.log(this.a);
}
}
Fn.prototype.write=function(){
console.log("write");
}
var f1 = new Fn;
var f2 = new Fn;
//检测是否为某个对象私有属性的方法hasOwnProperty
hasOwnProperty:检测某一个属性是否为这个对象的私有属性(只能检查私有的)
f1.hasOwnProperty("b") ==>true
//自己编写一个检测是否为某个对象公有属性的方法 hasPubProperty
function hasPubProperty(obj, attr) {
// var isAtr = attr in obj;
// var isOwnAtr = obj.hasOwnProperty(attr);
// var isPubAtr = false;
// if (isAtr == true && isOwnAtr == false) {
// isPubAtr = true;
// }
// return isPubAtr;
return (attr in obj) && !obj.hasOwnProperty(attr);
}
console.log(hasPubProperty(f1,"ss"));