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

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

    Sure it's possible. It's not recommended, but it's possible. For example:

    function a() {
        alert("a");
    }
    
    function b() {
        alert("b");
    }
    
    function c() {
        return c.f.apply(this, arguments);
    }
    
    c.f = a;
    
    c.toggle = function () {
        c.f = c.f === a ? b : a;
    };
    

    Now let's test it:

    c();        // alerts "a"
    c.toggle();
    c();        // alerts "b"
    

    See the demo: http://jsfiddle.net/LwKM3/

提交回复
热议问题