方法的一些对比(in 与 hasOwnProperty / typeof 与 instanceof)
1. in 与 hasOwnProperty
① in
👇
in
可以查找某对象是否有某一项属性
- 语法 ---------->
'keyName' in obj
属性名需要字符串形式- 而这样的查找,也会沿原型链不断查找 .__ proto __ ;
- 当前对象具有某属性时, 查找到返回
true
, 未查到返回false
// 当前对象本身具有某属性
let a = {name: 'haha'}
console.log('name' in a)
👆 上方例子为对象本身具有某属性 使用in
返回true
// 当前对象的原型链上有所查属性时
let a = {};
let b = {name: 'JavaScript'};
Object.setPrototypeOf(a,b)
// Object.setPrototypeOf(a,b) 是将 b对象设置为a对象的对象原型
console.log('name' in a)
// 输出true,因为沿原型链想上找 找到了b,b中有name属性
👆 上方例子为对象原型链上,具有某属性,使用in
返回true
Object.setPrototypeOf(a,b)
是将 b对象设置为a对象的对象原型,经过这样设置之后 a.__ proto __ === b
② hasOwnProperty
👇
hasOwnProperty
查找对象是否含有某属性
语法
obj.hasOwnProperty('keyName')
hasOwnProperty
只会查找对象本身是否有所查属性,返回 true / false不会沿着对象的原型链上的原型对象进行查找
let a = {name: 'haha'}
console.log(a.hasOwnProperty('name')) // 输出 true
在
for..in
语句中,会有hasOwnProperty
语法 👇
let a = {app: 'app'};
let b = {
name: 'JavaScript',
age: 10,
gender: '男'
};
Object.setPrototypeOf(a,b)
for (const key in a) {
console.log(key) // 依次输出 app name age gender
if (a.hasOwnProperty(key)) {
console.log(key) // 只输出 app
}
}
👆 在未经
hasOwnProperty
判断时,for..in
语句是会从原型链上查找, 将b中的属性都取出来 经过
hasOwnProperty
判断的if语句中, 只会取出对象本身存在的属性进行后续操作
2.判断数据类型 typeof 与 instanceof
① instanceof用法
a instanceof b
// a 一个实例 需要进行判断的项
// b 数据类型 Object Array Number String ...
- instanceof => 判断某实例对象是否是某个类型 返回true或false 左侧必须是对象形式(new出来的) 如字符串 必须通过new String()后才能进行判断 否则会返回false
- 数组与对象本身属于复杂数据类型 本身就已经实例化了。
*
instanceof也实质上用来检测某一个对象是否在另一个对象的原型链上 👇👇👇
function A(){}
let a = new A()
console.log(a instanceof A) // 输出true
console.log(a instanceof Object)
// 输出true 只要沿着a.__proto__....一直向上找,只要右侧对象.prototype与之相同 就返回true
*
判断数组可以通过该方法 而用typeof返回的永远是Object
var arr = [1,2,3]
console.log([1,2,3] instanceof Array); // 输出 true
var num = new Number(111)
console.log(111 instanceof Number,num instanceof Number); // 输出 false true
var obj = {name: 1}
console.log({name: 1} instanceof Object); // 输出 true
function a() { }
console.log(a instanceof Function); // 输出true
var str = 'hskdhahjkd'
var str1 = new String('jdshfjkkj')
console.log(str instanceof String, str1 instanceof String);// 输出 false true
console.log(typeof []); // => Object
② typeof用法
console.log(typeof a)
// a 被检查项
- typeof => 检查数据的数据类型 对传入的值不进行限制
- 如果变量未赋值 返回undefined
console.log(typeof a) // --> undefined
console.log(typeof 123) // --> Number
console.log(typeof 'a') // --> String
console.log(typeof []) // --> Object
console.log(typeof {}) // --> Object