2

here is my html

    <script src="game.js"></script>
    <script src="help.js"></script>
$(document).ready(function () {
    game = new Game();
    game.start();
})
</script>

game.js:

var Game = function() {
    this.start = function() {
        console.log('start');       
    };

};

help.js

Game.help = function() {
    alert('help');
}

however game.help() raises an error

What is wrong ? and how to fix it ?

Error: help is undefined

connexo
  • 53,704
  • 14
  • 91
  • 128
yarek
  • 11,278
  • 30
  • 120
  • 219
  • 1
    what error does it raise? – depperm Jul 29 '15 at 19:34
  • 1
    You added `help` to `Game` not to `game`. Try `Game.prototype.help = function() { ...}` – Matt Burland Jul 29 '15 at 19:35
  • 2
    duplicate http://stackoverflow.com/questions/13521833/javascript-add-method-to-object – Scott Puleo Jul 29 '15 at 19:36
  • The best way to create method is to use `Game.prototype.start = function(){}`. It will make just one function which will be written in Game's prototype instead of thousands functions you will create: one function for every Game's instance. – Ivan Jul 29 '15 at 19:38
  • You need prototypical inheritance, as stated by Matt Burland. – connexo Jul 29 '15 at 19:40

1 Answers1

5

First things first, Game.help will attach a function to the function Game, not to instances of the Game object.

That is, Game.help = function () { ... } will allow Game.help() but not new Game().help(). This is the equivalent of a static method in most OO languages.

What you can do, but isn't very idiomatic, is to change help.js to:

Game.prototype.help = function () {
  ...
}

This will attach the function as a method, so any instance of Game can have help() called on it.

Extending a class' prototype from another module(/file) is kind of sketchy, though, since it adds an implicit dependency (implicit preventing the browser from enforcing it, often leading to errors later when you forget about the dependency and change something that looks unrelated).

Until the ES7 extension methods proposal is finalized (and ES7) lands, you may want to consider using helper methods that take their scope as the first parameter:

help(game, ...) {
  alert('help for ' + game.name);
}

This is still less than ideal, but somewhat safer.

ssube
  • 47,010
  • 7
  • 103
  • 140