简体   繁体   English

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

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

In the code below, when somethingUseful.thisUsefulThing is called from setTimeout , can it reference somethingUseful.thatUsefulThing ? 在下面的代码中,当从setTimeout调用somethingUseful.thisUsefulThing时,它是否可以引用somethingUseful.thatUsefulThing

var somethingUseful = {
  thisUsefulThing: function() {
    this.thatUsefulThing();
  },

  thatUsefulThing: function() {
    console.log("I am useful!");
  }
}

setTimeout(somethingUseful.thisUsefulThing, 1000);

Right now, I am getting this error: 现在,我收到此错误:

Uncaught TypeError: Object [object global] has no method 'thatUsefulThing'

To simply answer your question, YES, thisUsefulThing CAN access thatUsefulThing 简单地回答你的问题,是的,这个有用的旅行可以访问那个有用的问题

But as your code currently runs, 'this' is not actually global, it is a reference to somethingUseful to all direct descendants itself. 但是当你的代码当前运行时,'this'实际上并不是全局的,它是对所有直接后代本身有用的东西的引用。

When I am working with literal objects, I usually reference them by name rather than with 'this', so in your case I would replace 'this.thatUsefulThing()' with somethingUseful.thatUsefulThing() 当我使用文字对象时,我通常用名字而不是'this'来引用它们,所以在你的情况下,我会用somethingUseful.thatUsefulThing()替换'this.thatUsefulThing()'

Why? 为什么? Because it works globally, anyway! 因为无论如何它在全球范围内运作!

EDIT: 编辑:

As plalx pointed out in his comment to my answer, best practices for implementing this class (with an example class member) would use functional classes / prototypes and look something like this: 正如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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM