代码之家  ›  专栏  ›  技术社区  ›  the_drow

我可以通过修改函数原型在对象构造期间执行操作吗?

  •  1
  • the_drow  · 技术社区  · 15 年前

    在构造新对象时,我想增加函数对象以执行更多操作。
    有可能吗?

    1 回复  |  直到 15 年前
        1
  •  2
  •   Prestaul    15 年前

    无法修改函数原型以便截获对函数的调用。最接近的方法是添加一个可以调用的方法来代替构造函数。例如:

    Function.prototype.create = function() {
        var obj = new this();  // instantiate the object
        this.apply(obj, arguments);  // call the constructor
    
        // do your stuff here (e.g. add properties or whatever it is you wanted to do)
        obj.foo = 'bar';
    
        return obj;
    };
    
    function SomeObject(name) {
        this.name = name;
    }
    
    var obj = SomeObject.create('Bob');
    obj.foo; // => 'bar'
    

    或者,您可以编写一个函数,调用它来构建一个构造函数:

    Function.makeConstructor = function(fn) {
        return function proxyConstructor() {
            // check to see if they called the function with the "new" operator
            if(this instanceof proxyConstructor) {
                var obj = new fn();
                fn.apply(obj, arguments);
    
                // do your stuff here (e.g. add properties or whatever it is you wanted to do)
                obj.foo = 'bar';
    
                return obj;
            } else {
                return fn.apply(null, arguments);
            }
        };
    };
    
    var SomeObject = Function.makeConstructor(function(name) {
        this.name = name;
    });
    
    var obj = SomeObject.create('Bob');
    obj.foo; // => 'bar'