0

Lets say I have a function called foo and I want function bar to inherit things from foo such as:

function foo(param1, param2, param3) {
    this.params = [param1, param2, param3];
    this.otherParameter = 3.141;
}
module.exports = foo;
foo.prototype.getParams = function(i, bool) {
    if(bool) {
        return this.params[i];
    }else{
        return this.otherParameter;
    }
};

var foo = require('./foo');
function bar() {
    this.barParams = [1, 2, 3, 4];
}

How would I make bar based off of foo like bar.prototype = new foo(1, 2, 3);? Should I use a bind function? If so, how?

Ian S.
  • 1,831
  • 9
  • 17

1 Answers1

0

This has to be a duplicate question, but: The usual way (before ES2015) is like this:

function bar(/*...args for bar...*/) {
    foo.call(this, /* appropriate arguments for foo */);
}
bar.prototype = Object.create(foo.prototype);
bar.prototype.constructor = bar;
T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
  • so if I had foo contain methods like addition and subtraction of numbers, and bar get those numbers, this would allow bar to add and subtract numbers using foo's methods? – Ian S. Jan 26 '16 at 19:27
  • and call foo methods via `this.add(barArg1, barArg2);` – Ian S. Jan 26 '16 at 19:29
  • Yes. `bar.prototype` inherits the methods from `foo.prototype`, and `bar` instances inherit them from `bar.prototype`. Then, the `bar` instance also gets any methods added by `foo` (e.g., within the `foo` constructor if you did `this.add = function() { ... })` because `foo` assigns them when we call it from `bar`. (BTW: Functions meant to be used with `new` should have an initial capital letter, e.g. `Foo` and `Bar`.) – T.J. Crowder Jan 26 '16 at 19:44
  • yeah so `foo.prototype.add = function() {};` and I can use in bar `this.add(1, 2);` then finally in a completely external function call `bar.add(1, 2);`? Sorry I'm only 12 and new to these intertwined functions. – Ian S. Jan 26 '16 at 19:53
  • @IanS.: Yes, that's how prototypical inheritance works. But note that `this` within a function isn't always the object you expect, because `this` is effectively a function argument. More: http://stackoverflow.com/questions/3127429/how-does-the-this-keyword-work – T.J. Crowder Jan 27 '16 at 08:16
  • @IanS.: With normal functions in JavaScript, `this` is effectively a function argument, and like other arguments, its value is set when the function is called. Things are slightly different for bound functions, and for arrow functions. – T.J. Crowder Jan 27 '16 at 16:47