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

前端 未结 6 1153
遥遥无期
遥遥无期 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:22

    Not sure if this helps, but I would implement described problem in following way:

    // defined by somebody else - unknown to developer
    var someFunction = function() {
        alert("this is initial behavior");
    }
    
    someFunction(); // returns "this is initial behavior"
    
    // defines parent object on which someFunction() is called
    var parentObject = this; // returns window object (as called direclty in the
    // browser)
    
    // if you are calling someFunction from some object (object.someFunction())
    // it would be:
    // var parentObject = object;
    
    // augumentThis definition
    someFunction.augumentThis = function() {
        var newFunction = function() {
            alert("this is changed behavior");
        };
        parentObject.someFunction.somePropertyFunction = function() {
            parentObject.someFunction = newFunction;
            parentObject.someFunction();
        };
    };
    
    someFunction.augumentThis();            // change function behavior
    someFunction();                         // "this is initial behavior"
    someFunction.somePropertyFunction();    // "this is changed behavior"
    someFunction();                         // "this is changed behavior"
    

提交回复
热议问题