简体   繁体   English

从构造函数中获取对象的所有javascript函数,但不是使用“ this”分配的函数?

[英]Get all javascript functions of an object from the constructor, BUT not those assigned using “this”?

I need to get all function names inside the constructor, excluding those functions assigned with this : 我需要获取构造函数内部的所有函数名称, 但要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. 我曾经用过Underscore.js,但没有运气。 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() {}

您需要原型定义的所有功能:

_.functions(MyObject.prototype);

The functions on this are those you have assigned inside the constructor plus those inherited from the prototype. 在功能this是那些你已经在构造函数中分配再加上那些从原型继承。 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 对于早期的IE,您可能会退回非标准

var funcs = _functions(this.__proto__);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM