JavaScript中的Object.assign和Object.setPrototypeOf有什么区别?

plm*_*k61 7 javascript inheritance

假设我有一个带有speak函数的动物对象:

function speak() {
  console.log(this.sound)
}

let animal = {
  speak
}
Run Code Online (Sandbox Code Playgroud)

我有一只狗sound:

let dog = {
  sound: "Woof!"
}
Run Code Online (Sandbox Code Playgroud)

如果我要dog继承speakanimal我可以使用Object.assignObject.setPrototypeOf.它们似乎产生了相同的结果:

let luke = Object.assign(dog, animal)

luke.speak() // Woof!

let bruno = Object.setPrototypeOf(dog, animal)

bruno.speak() // Woof!
Run Code Online (Sandbox Code Playgroud)

有什么区别,是一种被认为是"正确"的方式?

Abd*_*UMI 5

宾语.setPrototypeOf

 function(obj, proto) {
  obj.__proto__ = proto;
  return obj; 
}
Run Code Online (Sandbox Code Playgroud)

Object.assign:

function(target, ...varArgs) { // .length of function is 2
    'use strict';
    if (target == null) { // TypeError if undefined or null
      throw new TypeError('Cannot convert undefined or null to object');
    }

    var to = Object(target);

    for (var index = 1; index < arguments.length; index++) {
      var nextSource = arguments[index];

      if (nextSource != null) { // Skip over if undefined or null
        for (var nextKey in nextSource) {
          // Avoid bugs when hasOwnProperty is shadowed
          if (Object.prototype.hasOwnProperty.call(nextSource, nextKey)) {
            to[nextKey] = nextSource[nextKey];
          }
        }
      }
    }
    return to;
  };
Run Code Online (Sandbox Code Playgroud)

因此,setPrototypeOf只是将__proto__目标分配给源,但是,assign循环遍历参数(i)键并根据键通过参数(i + 1)值覆盖其值.