What are the differences from Object.create()
and Object.assign()
? Let’s explore!
- Test for prototypal relationships
Object.create
let dog = {
barks() {
console.log('woof woof');
}
}let menno = Object.create(dog);
Object.getPrototypeOf(menno) === dog; // true
dog.isPrototypeOf(menno); // true
Object.assign
let dog = {
barks() {
console.log('woof woof');
}
}let menno = Object.assign({}, dog);
Object.getPrototypeOf(menno) === dog; // false
dog.isPrototypeOf(menno); // false
2. Adding new property or method to a newly created object
Object.create
let dog = {
barks() {
console.log('woof woof');
}
}let menno = Object.create(dog, {
jumps: {
value: function () {
console.log('jumping!');
},
writable: false,
},
});menno.jumps(); // jumping
menno.barks(); // woof woof
Object.assign
let dog = {
barks() {
console.log('woof woof');
}
}let menno = Object.assign({}, dog, {
jumps() {
console.log('Jumping!');
}
});menno.jumps(); // jumping
menno.barks(); // woof woof
3. Access to methods up the prototypal chain
Object.create
let dog = {
barks() {
console.log('woof woof');
}
}let jackie = Object.create(dog);Object.defineProperties(jackie, {
swims: {
value: function() {
console.log('swimming swimming');
},
writable: false;
},
});let menno = Object.create(jackie);
menno.swims(); // swimming swimming
menno.barks(); // woof woof
Object.assign
let dog = {
barks() {
console.log('woof woof');
}
}let jackie = Object.create(dog);let menno = Object.assign({}, jackie);menno.barks(); // TypeError, menno.barks is not a function
4. Combine the deep cloning functionalities of Object.create()
with the flexibility of Object.assign()
Object.assign(Object.create(obj), ...sourceObjs)
let dog = {
barks() {
console.log('woof woof');
}
}let menno = Object.assign(Object.create(dog), {
swims() {
console.log('swimming swimming');
}
});
menno.swims(); // swimming swimming
menno.barks(); // woof woof