3

Say I have Dog.

function Dog(name) {
  this.name = name;
}

I want to namespace some functions on it's prototype.

Dog.prototype.movement = {
  this.run = this.name + 'is running',
  this.jump = function() { console.log(this.name + 'is jummping');}
}

So that I can call it like:

var carl = new Dog('Car');
carl.movement.jump();
//Carl is jumping.
Breedly
  • 12,838
  • 13
  • 59
  • 83
  • If you really want to do this, you have to add those functions in the constructor. See [Using 'this' within nested Prototype sub-objects](http://stackoverflow.com/q/28801859/218196) – Felix Kling May 13 '15 at 15:53

1 Answers1

3

You were close, just need to treat run and jump as object properties instead of variable assignments:

Dog.prototype = {
  movement: function() {
    return {
      run: function() { 
        this.name + 'is running' 
      }.bind(this),
      jump: function() { 
        console.log(this.name + ' is jummping');
      }.bind(this)
    }
  }
}

var carl = new Dog('Car');
carl.movement().jump();
Rob M.
  • 35,491
  • 6
  • 51
  • 50
  • 2
    How would you call those functions so that `this` refers to the `Dog` instance? – Felix Kling May 13 '15 at 15:51
  • I see, well in order to be in the context of `Dog`, you need make movement a method that returns the `run`/`jump` methods bound to the parent context, otherwise the scope will be bound to the movement object. I'll update my answer with an example. – Rob M. May 13 '15 at 16:02
  • I suppose I could use `call` instead of `bind` as well? Great answer by the way. And thanks @FelixKling for pointing to your answer. I need some time to try it out, but after I do I think you'll get my check mark @Rob M. – Breedly May 13 '15 at 18:21