JavaScript:函数字典:函数可以从其字典中引用函数
JavaScript: A dictionary of functions: Can a function reference functions from its dictionary?
在下面的代码中,当从setTimeout
调用somethingUseful.thisUsefulThing
时,它可以引用somethingUseful.thatUsefulThing
吗?
var somethingUseful = {
thisUsefulThing: function() {
this.thatUsefulThing();
},
thatUsefulThing: function() {
console.log("I am useful!");
}
}
setTimeout(somethingUseful.thisUsefulThing, 1000);
现在,我收到此错误:
Uncaught TypeError: Object [object global] has no method 'thatUsefulThing'
简单地回答你的问题,是的,这个有用的东西可以访问那个有用的东西
但是当你的代码目前运行时,"this"实际上并不是全局的,它是对所有直系后代本身有用的东西的引用。
当我使用文字对象时,我通常用名称而不是"this"来引用它们,所以在你的情况下,我会用somethingUseful.thatUsefulThing()替换"this.thatUsefulThing()"
为什么?因为它在全球范围内有效,无论如何!
编辑:
正如plalx在对我的回答的评论中指出的那样,实现此类(带有示例类成员)的最佳实践将使用函数类/原型,如下所示:
function SomethingUseful () {
this.member = 'I am a member';
}
SomethingUseful.prototype.thisUsefulThing = function () {
this.thatUsefulThing();
}
SomethingUseful.prototype.thatUsefulThing = function () {
console.log('I am useful, and ' + this.member);
}
usefulObject = new SomethingUseful();
usefulObject.thisUsefulThing(); // logs fine with access to this.member
setInterval(usefulObject.thisUsefulThing.bind(usefulObject), 1000); // has access to this.member through bind()
只需将this
值绑定到somethingUseful
即可。
setTimeout(somethingUseful.thisUsefulThing.bind(somethingUseful), 1000);
相关文章:
- 创建一个类似链接的按钮,并通过Javascript函数打开一个新的弹出窗口
- 将函数的上下文应用于javascript变量
- 如何在JavaScript中将字符串转换为函数引用
- 用嵌套函数和默认函数定义函数
- 使用 jQuery 的 .on 函数如何获取事件的原始元素
- javascript结合了数组和字典
- 无法导出函数expressjs/requestjs中的变量
- 在字典中存储函数[Python]
- 从iOS向javascript函数传递字典数组
- Javascript 将声明为函数字典的函数转换为原型
- 在 Javascript 中触发一个函数,如果单词在字典中
- JavaScript:函数字典:函数可以从其字典中引用函数
- JavaScript:以“常量”整数作为键的函数字典
- 使用函数参数值作为字典键
- 使用自定义函数从字典中创建列表/数组
- Javascript语法字典(标准函数、对象、方法和关键字)
- Typescript字典编码的有效Javascript字典函数到类
- 在javascript中使用标准数学函数更新字典
- 为什么单独定义JS原型函数比在字典中更快?
- 如何使用javascript(函数式编程)对特定键属性上的字典数组进行分组和转换