简体   繁体   English

这个继承是如何工作的?

[英]How does this inheritance work?

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.当我遇到上述类型的继承时,我正在阅读JavaScript Scene I am new to JS.我是 JS 新手。

So, proto is the object we will create a prototype from.因此, proto是我们将要从中创建原型的对象。

Que 1: If proto is an object, how does it have a function within it self without associating it with a key?问题 1:如果proto是一个对象,它如何在不将其与键相关联的情况下自身拥有函数? Shouldn't it be { "hello" : function(){...} }不应该是{ "hello" : function(){...} }

Related to that,与此相关,
Que 2: Can fat arrow functions be stored within objects as key-value pairs??问题 2:胖箭头函数可以作为键值对存储在对象中吗??

Que 3. How does Object.assign work? Que 3. Object.assign如何工作的?
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.阅读 MDN 后,我的理解是从第二个参数开始的所有内容都被复制到target ,在我们的例子中它是一个原型。 Correct?正确的?

Que 1: If proto is an object, how does it have a function within it self without associating it with a key?问题 1:如果 proto 是一个对象,它如何在不将其与键相关联的情况下在其自身内部拥有一个函数? Shouldn't it be { "hello" : function(){...} }不应该是 { "hello" : function(){...} }

This is because of the enw ES6 syntax of defining methods on an object.这是因为在对象上定义方法的 enw ES6 语法。 Refer this for details on the syntax: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Method_definitions有关语法的详细信息,请参阅此处: 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?问题 2:胖箭头函数可以作为键值对存储在对象中吗?

Yes.是的。 You can do it like below:你可以像下面这样做:

let obj = {
  func: () => {
    console.log(`Hello world!`);
  }
}

obj.func();

Que 3. How does Object.assign work? Que 3. Object.assign 是如何工作的?

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. Object.assign() 方法用于将所有可枚举属性的值从一个或多个源对象复制到目标对象。 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 .在您的情况下,它实际上不是原型,而是一个原型链接到proto的对象。 So your greeter returns an object which has name and the hello() method is from the prototype chain所以你的greeter返回一个有name的对象,而hello()方法来自原型链

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM