Object 与原型链的相关方法
Object.getPrototypeOf / Object.setPrototypeOf
获取原型对象/设置原型对象的标准方法。
js
function getPrototypeOf(obj){
return obj.__proto__
}
function setPrototypeOf(obj, proto){
obj.__proto__ = proto
return obj
}Object.create
基于一个对象为原型,创建新对象
js
function createFromObject(obj){
function c(){}
c.prototype = obj
return new c()
}补充:
js
// 特别地,三种方式是一模一样地
var obj1 = Object.create({});
var obj2 = Object.create(Object.prototype);
var obj3 = new Object();
// 第二个参数,属性描述符
var obj = Object.create({}, {
p1: {
value: 123,
enumerable: true,
configurable: true,
writable: true,
},
p2: {
value: 'abc',
enumerable: true,
configurable: true,
writable: true,
}
});
// 等同于
var obj = Object.create({});
obj.p1 = 123;
obj.p2 = 'abc';Object.prototype.isPrototypeOf
注意这是一个实例方法,可以判断实例是否是参数对象的原型,只要在原型链上,都是原型
in 与 for..in的穿透性
in 运算符返回一个布尔值,表示一个对象是否具有某个属性。它不区分该属性是对象自身的属性,还是继承的属性。
js
const o = {a:'1'}
const obj = Object.create(o)
obj.b = '2'
console.log('b' in obj) // true
console.log('a' in obj) // true
for(let key in obj){
console.log(key)
}
// b, a