obj.hasOwnProperty(prop) obj本身是否包含该属性(不包括原型链上的属性)
let obj = {
name:'112321',
age:18
}
Object.prototype.sex = '男'
for (const key in obj) {
console.log(key); //包括sex,包括原型链上的属性
if (obj.hasOwnProperty(key)) { //没有sex,只有自身的值
console.log(obj[key]);
}
}Object.getPrototypeOf(obj) 返回obj对象上的原型对象,三种获取原型对象的方法之一
function myInstanceof(left, right) {
let proto = Object.getPrototypeOf(left), // 获取对象的原型
prototype = right.prototype; // 获取构造函数的 prototype 对象
while (true) { // 判断构造函数的 prototype 对象是否在对象的原型链上
if (!proto) return false; //如果left的原型对象不存在则返回false
if (proto === prototype) return true; //如果left的原型对象于right相等,返回true
proto = Object.getPrototypeOf(proto); //获取left原型对象的原型对象,一直往上到不存在
}
}Object.assign(obj, ...sources) 将对象的可枚举属性赋值到obj上,属于浅拷贝的方法之一
const target = { a: 1, b: 2 };
const source = { b: 4, c: 5 };
const returnedTarget = Object.assign(target, source);
console.log(target);
// expected output: Object { a: 1, b: 4, c: 5 }
console.log(returnedTarget);
// expected output: Object { a: 1, b: 4, c: 5 }Object.create(proto[, propertiesObject])方法创建一个新对象,使用现有的对象来提供新创建的对象的__proto__。
const person = {
isHuman: false,
printIntroduction: function() {
console.log(`My name is ${this.name}. Am I human? ${this.isHuman}`);
}
};
const me = Object.create(person);
me.name = 'Matthew'; // "name" is a property set on "me", but not on "person"
me.isHuman = true; // inherited properties can be overwritten
me.printIntroduction();
// expected output: "My name is Matthew. Am I human? true"可枚举
const arr =[,12,3,212,null,undefined,'',true,false]
console.log(arr); //[empty, 12, 3, 212, null, undefined, "", true, false]
for(const i in arr){
arr[i]++
}
console.log(arr); //[empty, 13, 4, 213, 1, NaN, 1, 2, 1]
const flag = arr.hasOwnProperty('length')
console.log(flag); //true 数组中length为不可枚举属性,
//hasOwnProperty可以检测出自身不可枚举的属性