英文:
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: "Admin",
log() {
console.log(this.name);
}
};
const obj2 = {
name: "Moderator",
};
obj2.__proto__ = obj1;
obj2.log();
<!-- end snippet -->
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论