最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to call function from another function inside the same class - Stack Overflow

programmeradmin1浏览0评论

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 _binedTickCallback (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?

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 _binedTickCallback (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?

Share Improve this question asked Jan 23, 2017 at 21:01 TruzzeTruzze 1381 silver badge7 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 9

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.

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");
      }
    }
  );
}
发布评论

评论列表(0)

  1. 暂无评论