📜  Javascript Object.setPrototypeOf()

📅  最后修改于: 2020-09-27 06:56:53             🧑  作者: Mango

JavaScript Object.setPrototypeOf()方法将指定对象的原型设置为另一个对象或为null。

setPrototypeOf()方法的语法为:

Object.setPrototypeOf(obj, prototype)

setPrototypeOf()方法是一种静态方法,使用Object类名称进行调用。


setPrototypeOf()参数

setPrototypeOf()方法采用:

  • obj-要设置其原型的对象。
  • prototype-对象的新原型(对象或null)。

从setPrototypeOf()返回值
  • 返回指定的对象。

注意:在每个浏览器和JavaScript引擎中,更改对象的[[Prototype]]当前都是非常缓慢的操作。


示例1:使用Object.setPrototypeOf()
let Animal = {
  makeSound() {
    console.log(`${this.name}, ${this.sound}!`);
  },
};
// defining new Dog object
function Dog(name) {
  this.name = name;
  this.sound = "bark";
  // setting prototype to Animal
  Object.setPrototypeOf(this, Animal);
}

dog1 = new Dog("Marcus");

dog1.makeSound(); // Marcus, bark!

输出

Marcus, bark!

示例2:使用Object.setPrototypeOf()
let Animal = {
  makeSound() {
    console.log(`${this.name}, ${this.sound}!`);
  },
};
// defining object
class Dog {
  constructor(name, age) {
    this.name = name;
    this.sound = "bark";
  }
  introduce() {
    console.log(`I'm ${this.name}. I am ${this.age} years old.`);
  }
}
// Here Dog.prototype is passed as it is an object, while Dog is not an object
Object.setPrototypeOf(Dog.prototype, Animal);

dog1 = new Dog("Marcus", 3);

console.log(dog1);

dog1.makeSound(); // Marcus, bark!

输出

name: "Marcus"
 sound: "bark"
 __proto__:
     constructor: class Dog
     introduce: ƒ introduce()
      __proto__:
         makeSound: ƒ makeSound()
         __proto__: Object

Marcus, bark!

推荐阅读: Javascript对象isPrototypeOf()