我是新來的JavaScript,不能找出如何解決這個問題裏面。我目前正在嘗試創建一個個人推特機器人,它可以在新推文上提醒我,看到新的關注者等。我正在用node.js和npm軟件包Twit編寫這個機器人。我目前正在嘗試創建一個創建新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中它似乎並不喜歡這個工作。有人能幫我解決這個問題嗎?
非常感謝您的快速回答,現在它工作得很好,並且由於瀏覽器支持,這只是一個小個人機器人,只有我將在終端(cmd)中使用。再次感謝,祝你有美好的一天:) – Truzze
@Truzze當然!祝你有個美好的一天,不要忘記接受我的或者我的答案,以便讓人們知道如果他們遇到同樣的問題該怎麼辦! – furkle