const proto = {
hello () {
return `Hello, my name is ${ this.name }`;
}
};
const greeter = (name) => Object.assign(Object.create(proto), { name });
const george = greeter('george');
const msg = george.hello();
console.log(msg);
I was reading JavaScript Scene
when I came across the above type of inheritance. I am new to JS.
So, proto
is the object we will create a prototype from.
Que 1: If proto
is an object, how does it have a function within it self without associating it with a key? Shouldn't it be { "hello" : function(){...} }
Related to that,
Que 2: Can fat arrow functions be stored within objects as key-value pairs??
Que 3. How does Object.assign
work?
After reading MDN, what I understand is that everything from 2nd argument on is copied into the target
, which in our case is a prototype. Correct?
Que 1: If proto is an object, how does it have a function within it self without associating it with a key? Shouldn't it be { "hello" : function(){...} }
This is because of the enw ES6 syntax of defining methods on an object. Refer this for details on the syntax: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Method_definitions
Que 2: Can fat arrow functions be stored within objects as key-value pairs?
Yes. You can do it like below:
let obj = {
func: () => {
console.log(`Hello world!`);
}
}
obj.func();
Que 3. How does Object.assign work?
From the docs:
The Object.assign() method is used to copy the values of all enumerable own properties from one or more source objects to a target object. It will return the target object.
Object.assign(target, ...sources)
In your case its actually not prototype but an object which is prototypally-linked to proto
. So your greeter
returns an object which has name
and the hello()
method is from the prototype chain
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.