假设这是我的代码片段 让 myHeroes = ["雷神", "蜘蛛侠"];
让英雄力量 = { 雷神:“锤子”, 蜘蛛侠:“吊索”, getSpiderPower: 函数 () { 控制台.log(
spider power is ${this.spiderman}
);
}
};
heroPower.getSpiderPower();
heroPower.proto.getThorPower = function () { 返回
thor power is ${heroPower.thor}
;
};
heroPower.getThorPower();
现在,由于 javascript 中的常规对象无法访问原型,以便将此功能添加到对象 Heropower 中,我是否真的需要在对象名称后面编写 proto 来添加属性,还是有其他简单的方法?
我尝试使用heroPower.prototype.getThorPower=function(){..} 但这导致了错误 我希望在 HeroPower 对象中添加 get thorpower 函数,而无需在对象内部显式定义该函数,从对象外部插入它
heroPower.getThorPower = function () {
console.log(`thor power is ${this.thor}`);
return `thor power is ${this.thor}`;
}
您可以在不使用proto的情况下做到这一点。该技术用于 OOP 中的
Abstraction
。