Is it possible to modify a function itself when its property function is called?

前端 未结 6 1158
遥遥无期
遥遥无期 2021-01-28 13:02

Basically I want to do this:

someFunction() // do something

someFunction.somePropertyFunction()

someFunction()  // Now someFunction is modified; it should now          


        
6条回答
  •  面向向阳花
    2021-01-28 13:23

    I want to attach a function to Function.prototype. Then I need to bind a new function to the original function's name (which I'm not sure if it's possible).

    That indeed is impossible, you don't know what refers to the function. And you cannot change the internal representation of a function, which is immutable.

    The only thing you can do is to create a new function and return that, to let the caller of your method use it somehow - specifically assigning it to the original variable:

    somefunction = somefunction.augmentSomehow();
    

    Your method for that will look like this:

    Function.prototype.augmentSomehow = function() {
        var origFn = this;
        return function() {
            // in here, do something special
            // which might include invoking origFn() in a different way
        };
    };
    

提交回复
热议问题