0

I want to accomplish the following so that I can prototype a property of an object prototype. It's difficult to explain, so it's best illustrated with some code. The following code gives me undefined for this.name in the console. This is due to the failure of binding. But how can I accompish this, so that it works as expected:

var User = function(name) {
    this.name = name;
};

User.prototype.actions = {};

User.prototype.actions.eats = function(what) {
    console.log(this.name + ' eats ' + what);
};

User.prototype.actions.eats = function(what) {
    console.log(this.name + ' eats ' + what);
};

var Member = function(name) {
    User.call(this,name);
};

Member.prototype = Object.create(User.prototype);
Member.prototype.constructor = Member;

Member.prototype.actions.sleeps = function(time) {
    console.log(this.name + ' sleeps ' + time);
}

var user = new User('john');
var member = new Member('steward');

user.actions.eats('fries');

member.actions.eats('potatoes');
member.actions.sleeps('3 hours');
rsdrsd
  • 307
  • 1
  • 4
  • 13
  • What do you "expect" and what do you "get"? – Soren Sep 23 '15 at 18:11
  • 2
    The way you're setting up the prototype functions, as properties of another object ("actions"), is going to make it very messy to get it working. Why is it that you want that sub-object? – Pointy Sep 23 '15 at 18:13
  • 1
    More duplicates: https://stackoverflow.com/questions/15884096/organize-prototype-javascript-while-perserving-object-reference-and-inheritance, https://stackoverflow.com/questions/16502467/prototype-deep-scope-of-this-to-access-instances-scope – Felix Kling Sep 23 '15 at 18:16
  • In code which is executed I do something like user[namespace].eats('potatoes'). namespace can be actions or something else. The purpose is to group methods and to execute them on the object depending on the namespace. – rsdrsd Sep 23 '15 at 18:19

0 Answers0