-2

Want where I use the arrow function so it returns 'correct'.

let mama2 = {

    children:12,
    surname: true,
    town: 'umuadi',
    school:'imo state university', 
    mamaChild:() => {
        if (this.surname){
            return 'correct'
        }else{
            return 'failed'
        }
    }
}




let mama3 = {

    children:12,
    surname: true,
    town: 'umuadi',
    school:'imo state university', 
    mamaChild:function() {
        if (this.surname){
            return 'correct'
        }else{
            return 'failed'
        }
    }
}

I want to know the difference between this two codes why it gives me a different result.

when I run this code on my console the first code gives me the result of 'failed' and the second gives me the result of 'correct'.

clemens
  • 14,173
  • 11
  • 38
  • 52
Stanley
  • 1
  • 2
  • 2
    Arrow functions bind the context of `this` to the parent scope, which is not the object you are trying to refer to. That is not being done in the plain `function()`, hence why it works – Ben Rondeau Dec 02 '17 at 06:49
  • Possible duplicate of [How does the "this" keyword work?](https://stackoverflow.com/questions/3127429/how-does-the-this-keyword-work) – moon Dec 02 '17 at 06:50
  • https://derickbailey.com/2015/09/28/do-es6-arrow-functions-really-solve-this-in-javascript/ – A. Wolff Dec 02 '17 at 06:58

2 Answers2

2

When you use this inside arrow function it refers to window object. When you use this inside a normal function it refers to current object.

You can console log this in both cases to see the difference.

let mama2 = {
    children: 12,
    surname: true,
    town: 'umuadi',
    school: 'imo state university',
    mamaChild: () => {
        console.log(this); // window object
        if (this.surname) {
            return 'correct'
        } else {
            return 'failed'
        }
    }
}

mama2.mamaChild();

let mama3 = {
    children: 12,
    surname: true,
    town: 'umuadi',
    school: 'imo state university',
    mamaChild: function () {
        console.log(this); // mama3 object
        if (this.surname) {
            return 'correct'
        } else {
            return 'failed'
        }
    }
}

mama3.mamaChild();
Mohamed Abbas
  • 2,038
  • 1
  • 7
  • 19
0

Arrow functions bind the context of this to the outer scope, which in this case is not the object you are trying to reference. When you use a plain function(), this refers to the object with the value you are checking for.

Ben Rondeau
  • 2,793
  • 12
  • 20