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

时间:2009-07-14 19:20:28

标签: javascript constructor

我想在构造新对象时扩充Function对象以执行更多操作 有可能吗?

1 个答案:

答案 0 :(得分:2)

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

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'