【问题标题】:What is the difference between Object.assign and Object.setPrototypeOf in JavaScript?JavaScript 中的 Object.assign 和 Object.setPrototypeOf 有什么区别?
【发布时间】:2017-02-13 19:38:05
【问题描述】:

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

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

let animal = {
  speak
}

我有一只狗,他有sound

let dog = {
  sound: "Woof!"
}

如果我想让doganimal 继承speak,我可以使用Object.assignObject.setPrototypeOf。它们似乎产生了相同的结果:

let luke = Object.assign(dog, animal)

luke.speak() // Woof!

let bruno = Object.setPrototypeOf(dog, animal)

bruno.speak() // Woof!

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

【问题讨论】:

  • 嗯,一个很大的区别是你不应该使用Object.setPrototypeOf。如果要继承,请使用构造函数。
  • 主要区别在于 Object.assign 将使用第二个对象的属性覆盖第一个对象的属性,而 Object.setPrototypeOf 将创建一个从第一个对象到第二个对象的 [[Prototype]]。

标签: javascript inheritance


【解决方案1】:

对象。 setPrototypeOf

 function(obj, proto) {
  obj.__proto__ = proto;
  return obj; 
}

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;
  };

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-04-06
    • 1970-01-01
    • 2011-11-10
    • 1970-01-01
    • 2011-06-28
    • 2010-09-19
    • 2010-10-29
    相关资源
    最近更新 更多