📜  Javascript Object setPrototypeOf()方法

📅  最后修改于: 2020-10-25 11:47:54             🧑  作者: Mango

JavaScript Object.setPrototypeOf()方法

Object.setPrototypeOf()方法将指定对象的原型(即内部[[Prototype]]属性)设置为另一个对象或为null。所有JavaScript对象都从原型继承属性和方法。通常认为这是设置对象原型的正确方法。

句法:

Object.setPrototypeOf(obj, prototype)

参数:

obj:这是要设置其原型的对象。

原型:这是对象的新原型(对象或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"