JavaScript:函数字典:函数可以从其字典中引用函数

JavaScript: A dictionary of functions: Can a function reference functions from its dictionary?

本文关键字:函数 字典 引用 JavaScript      更新时间:2023-09-26

在下面的代码中,当从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);