简体   繁体   中英

How to call function from another function inside the same class

I'm new to javascript and can't figure out how to solve this problem. I'm currently trying to create a little personal twitter bot that 'alerts' me on new tweets, see new followers etc. I'm writing this bot with node.js and the npm package Twit. I'm currently trying to make a function that creates new Tweets. My problem is that i get a error from node.js if i try to run my code.

Here is my bot.js file

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.' });

My Class file

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
  }

}

My Error:

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)

My problem is that i can't call the functions (error or success) from my tweet function all inside my class TwitterBot. I'm used to write my code like this in 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
  }

But in javascript it doesn't seem to work like this. Can someone please help me with that problem?

Use an arrow function. One of the problems with the function() { } notation is that it changes this to the window object. If you use () => { } instead, the this reference should remain the value you wish it to (eg your class).

Here's a set of documentation on arrow functions . Note particularly the references to how arrow functions differ in terms of handling class variables like this and super .

The only possible downside of this is that arrow functions don't work in pre-ES6 locales, so you may need to use a transpiler like Babel if you need wide browser support in your project. Given that it's a server-side application, I doubt that'll be an issue, though.

You can avoid this by either binding the callback function passed to this.T.post() or by using an arrow-function. Change the tweet method to this:

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");
      }
    }
  );
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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