Refer to javascript function from within itself

后端 未结 12 896
失恋的感觉
失恋的感觉 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:32

    As rfw said, this is the most straight forward way to go if the function has one single name:

    var crazy = function() {
        console.log(crazy);
        console.log(crazy.isCrazy);
    };
    
    crazy.isCrazy = 'totally';
    crazy();
    

    In case it may have different names, or you wanted to pass it around, it must be wrapped in a closure:

    var crazy = (function(){
        var that = function() {
            console.log(that);
            console.log(that.isCrazy);
        };
        return that;
    })();
    
    crazy.isCrazy = 'totally';
    crazy();
    

提交回复
热议问题