Let's say I have an animal object with a speak
function:
function speak() {
console.log(this.sound)
}
let animal = {
speak
}
And I have a dog with a sound
:
let dog = {
sound: "Woof!"
}
If I want dog
to inherit speak
from animal
I can use Object.assign
or Object.setPrototypeOf
. They seem to produce the same results:
let luke = Object.assign(dog, animal)
luke.speak() // Woof!
let bruno = Object.setPrototypeOf(dog, animal)
bruno.speak() // Woof!
What is the difference and is one way considered the "right" way?
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;
};
Thus , setPrototypeOf
is just assign __proto__
of target to source, However, assign
loops through argument(i) keys and override its values by argument(i+1) values according to keys.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With