in运算符和hasOwnProperty()方法
in运算符
in
:用来检测某一个属性是否属于这个对象(可以检测私有/公有属性)。
举个栗子:
function Person(name){
this.name = name;
this.fn = function () {
console.log(this.name);
}
}
var p = new Person("Nicholas");
console.log("fn" in p); //=>true
in
只能判断fn
是p
的一个属性,但不能判断是公有属性还是私有属性。
hasOwnProperty()方法
hasOwnProperty()
:用来检测某一个属性是否为当前对象的私有属性(不管公有属性是否存在,只要私有中有就返回true)。
function Person(name){
this.name = name;
this.fn = function () {
console.log(this.name);
}
}
var p = new Person("Nicholas");
console.log(p.hasOwnProperty("fn")); //=>true
判断私有还是公有
- 检测私有属性:
p.hasOwnProperty("fn") //为true就是私有属性
- 检测公有属性:
("fn" in p) && (!p.hasOwnProperty("fn")) //为true就是公有属性