Refer to javascript function from within itself

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

    In order to make you code to work follow below

            function crazy_object (crazy) {
              this.isCrazy = crazy
            }
            
            var create_crazy = new crazy_object('hello') //creating object
            
            console.log(create_crazy); //=> { isCrazy = 'hello' }
            
            var crazy = function() {
                console.log(this); //=> { isCrazy = 'totally' }
                console.log(this.isCrazy); //=> 'totally'
            }
            
            create_crazy.isCrazy = 'totally'; //=> isCrazy = 'totally'
            //below we pass the created object in function crazy.
            //And doing that we can use the keywork `this` and refer to the object
            crazy.call(create_crazy, null);

    Using the call and apply method we can pass to a function a property,and in that function we can use the property with the keyword this

    For example:

    function speak (message) {
      console.log(`A person with name ${this.name} say ${message}`);
    }
    
    speak.call({ name: 'Roland' }, 'Javascript is awesome');

    To use it with property:

    function speak (message) {
      console.log(`A person with name ${this.name} say ${message}`);
    }
    
    var name = 'Roland'
    
    speak.call({ name }, 'Javascript is awesome');
    

提交回复
热议问题