javascript - 通常将上下文应用于方法别名
问题描述
我遇到了一个我无法解决的问题。不知道是知识匮乏,还是 Javascript 根本做不到,但我希望能了解一下。
我正在尝试在对象中执行函数别名列表。在执行这些函数时,我想使用它们,就好像它们是从实例本身执行的一样,所以我可以在被调用的方法中使用其他方法和实例变量。为了让我的解释更清楚一点,这里有一个例子:
class Bar {
constructor() {
this.name = "Bar";
}
someMethod() {
console.log(this.name) // should log Bar
}
}
class Foo {
constructor() {
this.name = "Foo";
}
someOtherMethod() {
console.log(this.name) // should log Foo
}
}
const bar = new Bar();
const foo = new Foo();
const methodList = {
foo: bar.someMethod,
baz: foo.someOtherMethod,
}
for(let prop in methodList) {
methodList[prop](); // logs 2x undefined
}
for(let prop in methodList) {
methodList[prop].apply(foo); //logs 2x Foo
}
从上面的例子可以看出,this.name
是类实例中的一个变量。执行第二个循环时,将应用上下文并按预期正确记录。我希望看到该上下文被自动应用,因为函数别名对象在不同的文件中执行,不知道foo
或bar
只是接收列表。
有什么办法可以做到这一点?
解决方案
您可以将您的foo
和bar
方法包装在它们自己的函数中。在这些方法中,您可以像这样在对象上调用对象的方法someMethod()
/ someOtherMethod()
:
const methodList = {
foo: (...args) => bar.someMethod(...args),
baz: (...args) => foo.someOtherMethod(...args),
}
目前,您的第一个循环不起作用,因为您this
没有引用对象的实际上下文,因为这不是用于调用该方法的内容。相反,它指的是您的methodList
请参见下面的示例:
class Bar {
constructor() {
this.name = "Bar";
}
someMethod() {
console.log(this.name) // should log Bar
}
}
class Foo {
constructor() {
this.name = "Foo";
}
someOtherMethod() {
console.log(this.name) // should log Foo
}
}
const bar = new Bar();
const foo = new Foo();
const methodList = {
foo: (...args) => bar.someMethod(...args),
baz: (...args) => foo.someOtherMethod(...args),
}
for(let prop in methodList) {
methodList[prop](); // correct logs
}
推荐阅读
- javascript - 如何从输入框中获取一些输入,放入变量中,然后使用 HTML 和 Javascript 输出到 span id?
- unity3d - UNITY 2D - 不能改变孩子的位置
- asp.net-mvc - Html.ActionLink 返回无样式的 PartialView
- java - 访问对象内对象的设置器
- react-native - 在 React Native 中使用 ScrollViews 水平和垂直滚动
- android - 导航抽屉活动设计未正确显示
- mysql - MySQL:LOAD DATA LOCAL INFILE 添加了额外的字符 '\r'
- javascript - 在分页中禁用通过触摸滚动
- delphi - 循环而不导致应用程序冻结
- electron - Electron 在主进程中处理 console.log 消息