开发者

How can I create inherited properties of functions without modifying the global Function.prototype?

Something like this works for the global Function.prototype.

Function.prototype.aaa = 1
(function () {}).aaa // => 1

But is there a way to put inherited properties of functions without changing开发者_C百科 Function.prototype?

function MyFunction () { return function () {} }
MyFunction.prototype.bbb = 2
// Can I have (new MyFunction).bbb ?


Your only other choice is to create your own Function factory function, since you've ruled out modifying the mechanism used by the standard Function factory. And of course, that's unlikely to do what you want it to do, since everyone would have to use your factory. :-)

Modifying the Function.prototype isn't necessarily evil. Prototype's been doing it for years, mostly to good effect.


function Wrap() {
    var f = new Function;
    /* for (var k in Wrap.prototype) {
        f[k] = Wrap.prototype[k];
    } 
    return f; */
    // return $.extend(f, Wrap.prototype);
    return _.extend(f, Wrap.prototype);
}

Wrap.prototype.foo = 42;

(Wrap()).foo === 42; // true

Create a new function then extend that function with properties from your Wrap.prototype.

Either use jQuery, underscore or a simple for loop.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜