setPrototypeOf
给对象设置一个新原型对象,即指向新的原型对象,跟原来的原型断开 。
function Exam(){
this.a = 1;
this.b = 2;
}
Exam.prototype.pro_a = 'pro_a';
let obj = new Exam();
console.log(obj.pro_a) // 'pro_a'
Object.setPrototypeOf(obj, {c: 3}); // 让obj对象指向一个新的原型
console.log(obj.pro_a) // 'undefne'
也可以使用Object.setPrototypeOf(Exam.prototype, {c: 3})来扩充(不是重置) Exam的原型
defineProperty
给对象扩充新属性
function Exam2(){
this.a = 1;
this.b =2;
}
let obj2 = new Exam2();
Object.defineProperty(obj2, 'd', { value: 4, enumerable: false,writable: true }); //defineProperty用于拓展实例的属性
// enumerable 设置为false for..in循环 & Object.keys方法 & JSON.stringify方法取不到该属性
for(let prop in obj2) {
console.log(prop); // a b
}
console.log(obj2) //a b d
console.log(new Exam2().d); //undefine
当然也可以用Object.defineProperty(Exam2.prototype, 'd', { value: 4,}); 来扩充原型属性;