0
function Person(name) {
    this.name = name;
}

Person.prototype.saySomething = function() {
     return 'say Something!';
}

let john = new Person('john');

//john {name: 'john', saySomething: function}

newObj = Object.assign(Object.create(john))

newObj is an empty {} with the john properties as a prototype. How does that differ from just doing newObj = Object.create(john); ?

1
  • 1
    Calling Object.assign with just one argument is indeed a useless call. Commented Feb 27, 2021 at 7:39

1 Answer 1

1

Object.assign is only useful when you provide more than one argument to it. It always returns the first argument it gets, which will be mutated by the other arguments. If you just provide one argument, there is no mutation happening, and so it is a no-operation really*.

Object.assign is sometimes called to populate a new object, created on-the-fly with {}, and then you see that this object is not a Person object:

function Person(name) {
    this.name = name;
}

Person.prototype.saySomething = function() {
     return 'say Something!';
}

let john = new Person('john');

//john {name: 'john', saySomething: function}

let created = Object.create(john);
let newObj = Object.assign({}, created);
console.log(created instanceof Person); // true
console.log(newObj instanceof Person); // false


* There is a border case where Object.assign still makes a difference when called with just one argument: that is when you pass it a primitive value. In that case it will act like the Object function, wrapping the primitive into an object.

Sign up to request clarification or add additional context in comments.

1 Comment

Did this answer your question? Could you leave some feed-back?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.