假设我有一个具有speak
功能的动物对象:
function speak() {
console.log(this.sound)
}
let animal = {
speak
}
我有一只狗,它会发出声音
:
let dog = {
sound: "Woof!"
}
如果我想让 dog
从 animal
继承 speak
我可以使用 Object.assign
或 对象.setPrototypeOf
。它们似乎产生相同的结果:
let luke = Object.assign(dog, animal)
luke.speak() // Woof!
let bruno = Object.setPrototypeOf(dog, animal)
bruno.speak() // Woof!
有什么区别,一种方式被认为是“正确”方式?
最佳答案
对象。设置原型(prototype)Of
function(obj, proto) {
obj.__proto__ = proto;
return obj;
}
对象.赋值:
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)值。
关于javascript - JavaScript 中的 Object.assign 和 Object.setPrototypeOf 有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42212174/