JavaScript原型继承到对象方法

huangapple go评论55阅读模式
英文:

JavaScript prototypical inheritance to object methods

问题

一个快速的问题。

我知道我可以创建一个类,并使用 "this" 关键字来做,但我是否可以通过原型继承的方式来替代呢?

示例:

const obj1 = {
name: "Admin",
log: () => console.log(obj1.name),
};


我创建了一个带有名称和一个打印 obj1 的名称的方法的对象。

const obj2 = {
name: "Moderator",
};

obj2.proto = obj1;


因此,我创建了另一个只带有名称而没有 log 方法的对象,然后通过原型继承,obj2 现在可以访问该方法,即使它没有使用它创建。

obj2.log();

// 输出:"Admin"


如何将 log 方法绑定到调用它的对象,以便通过原型继承使用它时,它将记录 obj2 的名称 "Moderator"?
英文:

one quick question.

I know i can make a class and do it with "this", keyword, but can i somehow do it alternatively via prototypical inheritance?

Example:

const obj1 = {
	name: "Admin",
	log: () => console.log(obj1.name),
};

I make a object with a name and a method that console.logs obj1's name

const obj2 = {
	name: "Moderator",
};

obj2.__proto__ = obj1;

So i make another object that only has a name, without log method, and i do prototypical inheritance so obj2 now has access to that method even if it's not created with it.

obj2.log();

// output: "Admin"

How can i bind log method to the object that calls it, so if i use it as obj2 through prototypical inheritance, it will log obj2's name "Moderator"

答案1

得分: 1

请使用常规函数而不是箭头函数,并访问this.name

const obj1 = {
    name: "Admin",
    log() {
        console.log(this.name);
    }
};
const obj2 = {
    name: "Moderator",
};
obj2.__proto__ = obj1;
obj2.log();
英文:

Use a regular function instead of an arrow function and access this.name.

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

const obj1 = {
    name: &quot;Admin&quot;,
    log() {
      console.log(this.name);
    }
};
const obj2 = {
    name: &quot;Moderator&quot;,
};
obj2.__proto__ = obj1;
obj2.log();

<!-- end snippet -->

huangapple
  • 本文由 发表于 2023年2月13日 23:50:50
  • 转载请务必保留本文链接:https://go.coder-hub.com/75438196.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定