Refer to javascript function from within itself

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

    how can I get the function to refer to itself?

    The idea of 'itself' does not exist with functions. What you need is an object and not just a function. An object has knowledge of itself available through the keyword 'this'. Within a function, 'this' points to the global object - in this case the window object. But if you use your function as a constructor function to create an object (using the new operator) then the object's 'this' pointer will point to the object itself.

    i.e this points to the object if you write:

    var anObject = new crazy();
    

    So you can re-write your code as follows:

    var crazy = function() {
        this.printMe = function(){
            console.log(this);
            console.log(this.isCrazy); 
        }
    }
    
    var anObject = new crazy(); //create an object
    anObject.isCrazy = 'totally'; //add a new property to the object
    anObject.printMe(); //now print
    

    In case you wish to add the property before the object is created, then you have to add the property to the function's prototype as follows:

    var crazy = function() {
        console.log(this);
        console.log(this.isCrazy); 
    }
    
    crazy.prototype.isCrazy = 'totally'; //add the property to the function's prototype
    var anObject = new crazy(); //invoke the constructor
    

    See more on my blog for a detailed explanation of these concepts with code-samples.

提交回复
热议问题