Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 214
Truzze Avatar asked Jan 23 '17 21:01

Truzze


People also ask

How do I call a function from another function in the same class?

Example: public class CallingMethodsInSameClass { // Method definition performing a Call to another Method public static void main(String[] args) { Method1(); // Method being called. Method2(); // Method being called. } // Method definition to call in another Method public static void Method1() { System. out.

How do you call a function inside another function?

To call a function inside another function, define the inner function inside the outer function and invoke it. When using the function keyword, the function gets hoisted to the top of the scope and can be called from anywhere inside of the outer function.

Can you call a function from another function?

It is important to understand that each of the functions we write can be used and called from other functions we write. This is one of the most important ways that computer scientists take a large problem and break it down into a group of smaller problems.


2 Answers

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 (e.g. 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.

like image 146
furkle Avatar answered Oct 11 '22 07:10

furkle


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");
      }
    }
  );
}
like image 44
idbehold Avatar answered Oct 11 '22 07:10

idbehold