Refer to javascript function from within itself

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

    You can use the call method

    var crazy = function() {
        console.log(this);
        console.log(this.isCrazy);
    }
    crazy.isCrazy = 'totally';
    crazy.call(crazy);
    // calls crazy using crazy as the target, instead of window:
    // functionToCall.call(objectToUseForThis);
    

    Though if your function only ever has one name, you can do this:

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

提交回复
热议问题