JavaScript Object.setPrototypeOf() 方法
Object.setPrototypeOf() 方法将指定对象的原型(即内部的[[Prototype]]属性)设置为另一个对象或null。所有的JavaScript对象都继承了原型的属性和方法。通常认为这是设置对象原型的正确方式。
语法:
Object.setPrototypeOf(obj, prototype)
参数:
obj :被设置原型的对象。
Prototype :对象的新原型(一个对象或null)。
返回值:
该方法返回指定的对象。
浏览器支持:
Chrome | 34 |
---|---|
Edge | Yes |
Firefox | 31 |
Opera | Yes |
示例1
let raay = {
drive() {
return 'Add raay';
}
}
let naty = {
net() {
return 'use net';
}
}
// Set raay's __proto__ to naty's __proto__'s __proto__
Object.setPrototypeOf(naty, raay);
console.dir(naty); //prints the naty object
console.log(naty.net()); // use net
console.log(naty.drive()); // Add raay
输出:
[object Object] {
drive: drive() {
return 'Add raay';
},
net: net() {
return 'use net';
}
}
"use net"
"Add raay"
示例2
var Animal = {
speak() {
console.log(this.name + ' makes');
}
};
class Dog {
constructor(name) {
this.name = name;
}
}
Object.setPrototypeOf(Dog.prototype, Animal);
// If you do not do this you will get a TypeError when you invoke speak
var d = new Dog('people');
d.speak();
输出:
"people makes"
示例3
let toyota = {
drive() {
return 'driving toyota';
}
}
let camry = {
wifi() {
return 'carry';
}
}
// Set toyota's __proto__ to camry's __proto__'s __proto__
Object.setPrototypeOf(camry, toyota);
console.dir(camry); //prints the camry object
console.log(camry.wifi()); // carry
输出:
[object Object] {
drive: drive() {
return 'driving toyota';
},
wifi: wifi() {
return 'carry';
}
}
"carry"