假设我有一个speak
函数的动物对象:
function speak() {
console.log(this.sound)
}
let animal = {
speak
}
我有一只sound
的狗:
let dog = {
sound: "Woof!"
}
如果我希望dog
从speak
继承animal
,我可以使用Object.assign
或Object.setPrototypeOf
。它们似乎产生了相同的结果:
let luke = Object.assign(dog, animal)
luke.speak() // Woof!
let bruno = Object.setPrototypeOf(dog, animal)
bruno.speak() // Woof!
有什么区别,是一种被认为是"对"方式是什么?
答案 0 :(得分:5)
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)值覆盖其值钥匙。