JavaScript function redefinition

后端 未结 6 1320
梦毁少年i
梦毁少年i 2020-12-15 06:51

Is it possible to redefine a JavaScript function from within its own body. For example, could I do the following?

function never_called_again(args) {
  // Do         


        
6条回答
  •  眼角桃花
    2020-12-15 07:14

    It's totally possible to redefine a function object into whatever you want upon the first call.

    The reason this is possible is because the assignment evaluations is handled from right to left. This means that the scope of the function is captured when you execute it (in this case, when you call the function).

    This really means that at the time of execution, the function object that is getting executed and the original function definition are actually two different things, which allows redefinition of the original function as, well... anything really.

    One of the best (and coolest) ways to use this is by creating a function that is, in essence, its own factory. In this way you don't have to carry around a lot of object definitions that aren't going to be used.

    Example:

    d = function(type){
        switch(type.toUpperCase()){
            case 'A' :
                d = (
                        function(){
                            return {
                                name : 'A',
                                getName : function(){return this.name;}
                            };
                        }
                    )();
                    break;
    
            case 'B' :
                d = (
                    function(){
                        return {
                            name : 'B',
                            getName : function(){return this.name;}
                        };
                    }
                )();
                break;
    
            default:
                d = (
                    function(){
                        return {
                            name : 'DEFAULT',
                            getName : function(){return this.name;}
                        };
                    }
                )();
                break;
        }
    };
    
    console.dir(d);
    d('A');
    console.dir(d);
    console.log(d.getName());
    

提交回复
热议问题