views:

62

answers:

2

I'd like to augment the Function object to do more operations while constructing a new object.
Is it possible?

A: 

Look FUNCTION AS AN OBJECT

rodrigoap
I don't see how that's relevant to adding operations into the Function ctor.
the_drow
+2  A: 

There is no way to modify the Function prototype so that you can intercept calls to a function. The closest you are going to get to this is to add a method that you can call in place of a constructor. For example:

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'

Alternatively you could write a function that you would call to build a constructor:

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'
Prestaul
can't you just hook up an event?
the_drow
There is no event that triggers anytime you call an object constructor. The javascript object model is not associated with the DOM API which is where the browser event model lives. I really think these are as close as you are going to get.
Prestaul