对象方法的补充
Object.create()
使用指定的原型对象和属性创建一个新对象。
返回值:一个新对象,带着指定的原型对象和属性。
var obj = {
name: "why",
age: 18
}
// 指定新对象的原型为obj
var info = Object.create(obj, {
address: {
configurable: true,
writable: true,
enumerable: true,
value: "beijing"
}
})
console.log(info)
Object.assign()
通过复制一个或多个对象来创建一个新的对象。
const target = { a: 1, b: 2 };
const source = { c: 4, d: 5 };
// 原对象target也会发生变化
// const res = Object.assign(target, source)
// 解决方案1
const res1 = Object.assign({}, target, source)
// 解决方案2
const res2 = {...target, ...source}
Object.defineProperty()
给对象添加一个属性并指定该属性的配置。
const obj = {};
Object.defineProperty(obj, "address", {
value: "深圳",
configurable: true,
enumerable: true,
writable: true
})
Object.defineProperties()
给对象添加多个属性并分别指定它们的配置。
const obj = {};
Object.defineProperties(obj, {
address: {
value: "深圳",
configurable: true,
enumerable: true,
writable: true
},
name: {
value: "malong",
configurable: true,
enumerable: true,
writable: true
}
})
Object.entries()
返回给定对象自身可枚举属性的 [key, value] 数组。
const obj = {
name: "malong"
}
Object.defineProperty(obj, "address", {
value: "不可枚举",
enumerable: false,
configurable: true,
writable: true
})
const res = Object.entries(obj)
console.log(res)
Object.freeze()
冻结对象:其他代码不能删除或更改任何属性。
var obj = {
name: "malong"
};
Object.freeze(obj)
Object.prototype.hasOwnProperty()
返回一个布尔值,用于表示一个对象自身是否包含指定的属性,该方法并不会查找原型链上继承来的属性。
var obj = {
name: "zhangsan"
}
for(var key in obj){
if(obj.hasOwnProperty(key)){
console.log(obj[key])
}
}
instanceof
instanceof 运算符用于检测构造函数的 prototype 属性是否出现在某个实例对象的原型链上。
function inheritPrototype(SubType, SuperType) {
SubType.prototype = Object.create(SuperType.prototype)
Object.defineProperty(SubType.prototype, "constructor", {
enumerable: false,
configurable: true,
writable: true,
value: SubType
})
}
function Person() {
}
function Student() {
}
inheritPrototype(Student, Person)
var stu = new Student()
// instanceof 只能检测构造函数
console.log(stu instanceof Student) // true
console.log(stu instanceof Person) // true
console.log(stu instanceof Object) // true
# Object.prototype.isPrototypeOf()
isPrototypeOf() 方法用于测试一个对象是否存在于另一个对象的原型链上。
isPrototypeOf()与instanceof运算符不同。在表达式 "object instanceof AFunction"中,object的原型链是针对AFunction.prototype进行检查的,而不是针对AFunction本身。
var obj = {
name: "malong",
age: 18
}
var info = Object.create(obj)
// instanceof 就用不了了
// console.log(info instanceof obj)
console.log(obj.isPrototypeOf(info))
// 更多API参考MDN : https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Object