如何从同一个类中的另一个函数调用函数

我是新来的JavaScript,不知道如何解决这个问题。 我目前正在尝试创build一个个人推特机器人,它可以在新的推文上提醒我,看到新的追随者等等。我正在用node.js和npm软件包Twit编写这个机器人。 我目前正在尝试创build一个新的Tweets函数。 我的问题是,我从node.js得到一个错误,如果我尝试运行我的代码。

这是我的bot.js文件

var config = require("./app/config"); var TwitterBot = require("./app/classes/TwitterBot"); var Twit = require("twit"); var T = new Twit(config); var app = new TwitterBot(T); app.tweet({ text: 'This is my test Tweet.' }); 

我的类文件

 module.exports = class TwitterBot { constructor(T) { this.T = T; this.colors = require('colors/safe'); console.log("Class works"); } tweet(data) { this.T.post( 'statuses/update', { status: data.text }, function(err, data, response) { if (err) { this.error("Something went wrong"); } else { this.success("Tweet successfully created"); } } ); } error(something) { console.log("Error: " + something); // This is just an example in my code it performs a switch function } success(something) { console.log("Success: " + something); // This is just an example in my code it performs a switch function } } 

我的错误:

 Class works C:\Users\Colin\Desktop\Twitter-Bot\app\classes\TwitterBot.js:14 this.error('tweet', err); ^ TypeError: Cannot read property 'error' of undefined at C:\Users\Colin\Desktop\Twitter-Bot\app\classes\TwitterBot.js:14:15 at C:\Users\Colin\Desktop\Twitter-Bot\node_modules\twit\lib\twitter.js:118:13 at onRequestComplete (C:\Users\Colin\Desktop\Twitter-Bot\node_modules\twit\lib\twitter.js:324:7) at Request.<anonymous> (C:\Users\Colin\Desktop\Twitter-Bot\node_modules\twit\lib\twitter.js:341:7) at emitOne (events.js:101:20) at Request.emit (events.js:188:7) at Gunzip.<anonymous> (C:\Users\Colin\Desktop\Twitter-Bot\node_modules\request\request.js:1001:12) at Gunzip.g (events.js:291:16) at emitNone (events.js:91:20) at Gunzip.emit (events.js:185:7) at endReadableNT (_stream_readable.js:974:12) at _combinedTickCallback (internal/process/next_tick.js:74:11) at process._tickCallback (internal/process/next_tick.js:98:9) 

我的问题是,我不能从我的类TwitterBot里面的我的推特函数中调用函数(错误或成功)。 我习惯在php中这样写我的代码

  public function tweet($text) { // ... Some function that sends the tweet and returns ($err, $data, $response) if ($err) { // I call other functions inside the same class with $this->functionName(); $this->error($err); } } protected function error($err) { // do something with the $err variable } 

但在JavaScript中,它似乎并没有像这样工作。 有人可以帮我解决这个问题吗?

使用箭头function。 function() { }表示法的问题之一是它将其更改为窗口对象。 如果你使用() => { } ,那么this引用应该保持你想要的值(例如你的类)。

这是一组关于箭头函数的文档。 请特别注意箭头函数在处理像thissuper这样的类variables方面的不同之处。

唯一可能的缺点就是箭头函数在ES6之前版本中不起作用,所以如果你的项目需要浏览器的支持,你可能需要使用像Babel这样的转译器。 鉴于这是一个服务器端应用程序,我怀疑这将是一个问题,但。

您可以通过绑定传递给this.T.post()的callback函数或使用箭头函数来避免这种情况。 tweet方法更改为:

 tweet(data) { this.T.post( 'statuses/update', { status: data.text }, (err, data, response) => { // this line got changed if (err) { this.error("Something went wrong"); } else { this.success("Tweet successfully created"); } } ); }