1

In my little brain I can't explain how to refer correctly to method in object's prototype:

function A(){}
A.prototype.action = function(){}
A.prototype.dict = { action: this.action } // Mistake here.
var a = new A();
a.dict.action(); // -> undefined, but I expect a call of 'A.prototype.action' or other function if I override it in 'a'
  • 1
    `a = new A;` should be `var a = new A()`; when you get the rest of it working. What is it you're trying to achieve with that code? – Andy Apr 09 '15 at 12:33
  • And please use `var` where appropriate and be consistent with semi-colons. You (and your colleagues) will thank you someday. – Cᴏʀʏ Apr 09 '15 at 12:34
  • @Cᴏʀʏ, It's just a quick-typed example of my problem. Of course, I always use 'var' and semi-colons. – Dmitry Logvinenko Apr 09 '15 at 12:41
  • What's the `dict` method doing? Why can't you just call `a.action()`? – Andy Apr 09 '15 at 12:42
  • @Andy, I just need to place references to prototype's methods in object. This object is a map of strings (text representation of events' type) and corresponding actions (functions). This object used as default and could be overrided in inherited object. – Dmitry Logvinenko Apr 09 '15 at 12:53
  • @Andy, `dict` is not a method. It's just dictionary, which has to be available in prototype. – Dmitry Logvinenko Apr 09 '15 at 16:21

1 Answers1

0

You haven't really explained why you need this functionality, but the following should help you avoid the errors you're seeing. Whether this is good practice or not I leave up to you to research.

function A() {
    var self = this;
    this.dict = {
        action: function() {
            // by default, A.dict.action calls A.action
            return self.action();
        }
    };
}

// Define A.action
A.prototype.action = function() {
    console.log('prototype');
};

// Let's test it out
var a = new A();
a.dict.action(); // prints 'prototype'

// Override it on instance a
a.dict.action = function() {
  console.log('overridden');
};
a.dict.action(); // prints 'overridden'

// Let's create a new instance of A: b
var b = new A();
b.dict.action(); // prints 'prototpye'
Cᴏʀʏ
  • 105,112
  • 20
  • 162
  • 194