Object.setPrototypeOf()
方法将指定对象的原型设置为另一个对象或 null
。
示例
// create an empty object
const obj = {};
// create a non-empty object parent
const parent = { foo: 'bar' };
// set parent as the prototype of obj
Object.setPrototypeOf(obj, parent);
// print foo property of parent
// using the obj object
console.log(obj.foo);
// Output: "bar"
setPrototypeOf() 语法
setPrototypeOf()
方法的语法是:
Object.setPrototypeOf(obj, prototype)
setPrototypeOf()
方法是静态方法,通过 Object
类名调用。
setPrototypeOf() 参数
setPrototypeOf()
方法接受以下参数:
- obj - 我们想要设置其原型的对象。
- prototype - 对象的第一个原型(一个对象或 null)。
setPrototypeOf() 返回值
setPrototypeOf()
方法返回我们想要设置其原型的对象,即 obj。
注意:目前,在所有浏览器和 JavaScript 引擎中,更改对象的 [[Prototype]]
都是一个非常缓慢的操作。
示例 1:JavaScript Object.setPrototypeOf()
// create the object to be set as the prototype
let Animal = {
makeSound() {
console.log(`${this.name}, ${this.sound}!`);
},
};
// define the Dog object constructor
function Dog(name) {
this.name = name;
this.sound = "bark";
// set prototype of Dog object to Animal
Object.setPrototypeOf(this, Animal);
}
// create dog1 object using the Dog() constructor
dog1 = new Dog("Marcus");
// call the makeSound() method of Animal
dog1.makeSound();
// Output: Marcus, bark!
在上面的示例中,使用 Object.setPrototypeOf()
方法将 Animal 对象设置为 dog1 对象的原型。
因此,即使 makeSound()
方法没有在 Dog()
构造函数内部定义,我们仍然可以通过 dog1 对象访问 Animal 的 makeSound()
方法。
示例 2:在类中使用 setPrototypeOf()
// create the object to be set as prototype
let Animal = {
makeSound() {
console.log(`${this.name}, ${this.sound}!`);
},
};
// create the Dog class
class Dog {
constructor(name) {
this.name = name;
this.sound = "bark";
}
}
// Dog is a class, so
// Dog.prototype is an object
Object.setPrototypeOf(Dog.prototype, Animal);
// create an object of Dog class
let dog1 = new Dog("Marcus");
// print properties of dog1
console.log(dog1);
// Output: { name: 'Marcus', sound: 'bark' }
// call the makeSound() method of Animal
dog1.makeSound();
// Output: Marcus, bark!
在上面的示例中,setPrototypeOf()
方法用于将 Dog 类的对象的原型设置为 Animal 对象。
因此,Dog 类的所有实例(在本例中为 dog1)都可以继承并调用 Animal 对象中的 makeSound()
方法。
另请阅读