Refer to javascript function from within itself

后端 未结 12 895
失恋的感觉
失恋的感觉 2020-12-24 06:08

Consider this piece of code

var crazy = function() {
    console.log(this);
    console.log(this.isCrazy); // wrong.
}
crazy.isCrazy = \'totally\';
crazy();
         


        
12条回答
  •  攒了一身酷
    2020-12-24 06:55

    Personally I feel that the correct way to use a function inside of a function would be to use a constructor inside of a constructor, because of the keyword 'this':

        this;
    

    Defining functions and reusing them within themselves gives the developer no control over scopes. In a real-life use-case, even it everything looked as if the function called within its-self seemed to be working perfectly, there is no way in h*ll I would put it into a production piece of code. By creating an object and assigning parameter values to variables using the 'this' key word like so:

        new SumObj{
          constructor(delta, epsilon, zeta){
              this.delta = delta;
              this.epsilon = epsilon;
              this.zeta = zeta;
          }
        }
    

    You are essentially controlling the scopes of the different layers of variables that have the same name. Not controlling the scopes of variables in such a case is very likely to cause the developer much grief.

        new SumObj('someStr', 300, true);
    

    Using an Object in such a way will create a new instance with a unique scope of its own, therefore; this allows you to trust the values of your variables, and you will not get surprise results.

    • Bellow is a very simple use, that is actually practical to use in a real world app. I use an object similar to this for printing when testing Node.JS projects I am working on.

    class PrintObj {
        constructor(obj) {
            this.vals = Object.values(obj);
            this.keys = Object.keys(obj);
    
            for(let i = 0; i < this.vals.length; i++) {
                const el = this.vals[i];
    
                if(typeof el === 'object'){ 
                    new PrintObj(el);
                } else {
                    console.log(`\t ${this.keys[i]} : ` + el);
                }
            }
        }
    }
    
    const sumObj = {
        alpha: 'Hello World!',
        beta: 'Hello From Universe!',
        gamma: 'Hello Developers!',
        delta: {
            a: '0',
            b: '1',
            c: '2',
            e: '3',
            f: '4',
        },
        epsilon : 'Hello Mum',
        zeta : 'Hello Papa'
    };
    new PrintObj(sumObj);

提交回复
热议问题