1、验证一个属性是否属于这个对象:attr in object
2、验证一个属性是否是一个对象的私有属性:[object].hasOwnProperty([attr])
3、例子
function Fn(x, y) {
let total = x + y;
this.x = x;
this.y = y;
this.say = function () {};
return total;
}
let f = new Fn(10, 20);
// console.log('say' in f); //->true
// console.log(f.hasOwnProperty('say')); //->true
// console.log('toString' in f); //->true
// console.log(f.hasOwnProperty('toString')); //->false
// console.log(f.hasOwnProperty('hasOwnProperty')); //->false
4、验证一个属性是对象公有的属性「是它的属性,还不是私有的属性」简单写法不太正确
弊端:某个属性既是私有的,也是公有的
function hasPubProperty(obj, attr) {
return (attr in obj) && !obj.hasOwnProperty(attr);
}
// console.log(hasPubProperty(f, 'hasOwnProperty')); //->true
5、验证某个实例是否率属于这个类 instanceof
/* console.log(f instanceof Fn); //->true
console.log(f instanceof Array); //->false
console.log(f instanceof Object); //->true */
/* console.log(1 instanceof Number); //->false
console.log(new Number(1) instanceof Number); //->true */
6、new 执行
function Fn(x, y) {
let total = x + y;
this.x = x;
this.y = y;
this.say = function () {};
return total;
}
let f = new Fn(10, 20);
let f2 = new Fn; //这样也会把Fn执行,也会创建其实例对象
// new Fn VS new Fn()
// + 第二个可以传递实参,第一个不能
// + 运算符优先级的区别
// 运算符优先级
// https://developer.mozilla.org/zh-cn/docs/web/javascript/reference/operators/operator_precedence
// + new Fn() 20
// + new Fn 19
// + 成员访问 obj.xx 20
7、例子 (1)先执行new Fn() 再执行 实例.say()
/* new Fn().say()
// + new Fn()
// + 实例.say() */
(2) 先执行Fn.say() 再执行new V()
/* new Fn.say();
// + Fn.say 值V
// + new V() */