0

I need to get all function names inside the constructor, excluding those functions assigned with this:

var MyObject = function (arg1, arg2) {
    this.arg1 = arg1;
    this.arg2 = arg2;

    // Get all functions, i.e. 'foo', excluding 'arg1' and 'arg2'
};

MyObject.prototype.foo = function() {}

I have used Underscore.js, without luck. Assuming that the actual parameters are both functions:

var MyObject = function (arg1, arg2) {
    this.arg1 = arg1;
    this.arg2 = arg2;

    // Array of object function names, that is 'foo', 'arg1' and 'arg2'
    var functions = _.functions(this);

     // Loop over function names
    _.each(functions, function (name) {}, this) {
        // Function arguments contain this.name? Strict check ===
        if(_.contains(arguments, this.name) {
            functions = _.without(functions, name); // Remove this function
        }
    }
};

MyObject.prototype.foo = function() {}
gremo
  • 47,186
  • 75
  • 257
  • 421

2 Answers2

2

You're asking for all of the functions defined by the prototype:

_.functions(MyObject.prototype);
SLaks
  • 868,454
  • 176
  • 1,908
  • 1,964
  • Of course, thanks!!! Mind if I ask you to help me with [this related question](http://stackoverflow.com/questions/14946201/why-the-execution-context-this-of-prototypical-function-is-wrong-in-this-exa)? – gremo Feb 18 '13 at 22:09
  • Note that this will only return enumerable functions and will also get those on the prototype's `[[Prototype]]` as there is no `ownProperty` test. And since underscore uses `typeof` to test for functions, it will likely fail for host objects in some browsers (i.e. not return callable enumerable properties). – RobG Feb 18 '13 at 22:26
1

The functions on this are those you have assigned inside the constructor plus those inherited from the prototype. So what you need to do is query the prototype for its functions:

var funcs = _functions(Object.getPrototypeOf(this));

The above works in all reasonably modern browsers. For early IE you could fall back to the non-standard

var funcs = _functions(this.__proto__);
Jon
  • 428,835
  • 81
  • 738
  • 806