Skip to content
Advertisement

Using `this` for Parent Function inside a Nested Function

In the Apple “classs”, how can the nested function countSeeds() retrieve the value this.price?

jsfiddle: http://jsfiddle.net/VGqEa/

Apple = function() {
    this.price = 17

    this.cutOpen = function() {

        console.log(this.price);
        countSeeds();

        function countSeeds() {
            console.log(this.price);
        }
    }        
}


var apple = new Apple();
apple.cutOpen();

Output

17
undefined

Advertisement

Answer

put var self = this at the top of Apple, and then refer to this as self instead in the nested function.

i.e.:

Apple = function() {
    var self = this;
    this.price = 17

    this.cutOpen = function() {

        console.log(this.price);
        countSeeds();

        function countSeeds() {
            console.log(self.price);
        }
    }        
}


var apple = new Apple();
apple.cutOpen();

You could also put the self=this statement at the beginning of this.cutOpen, since this will still refer to the Apple object in cutOpen (since it is a method of Apple).

Update

Most evergreen browsers now support arrow functions, so you can write it like:

Apple = function() {
    this.price = 17

    this.cutOpen = function() {

        console.log(this.price);
        let countSeeds = () => {
            console.log(this.price);
        };
        countSeeds();
    }        
}

This doesn’t work in IE11 or other older browsers, unless you use some kind of transpiler to target older javascript.

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement