-3
let me = {
    name: "Sina",

    talk: ()=>
    {
      return this.name;
    }, 

    setName: (newName)=>
    {
        this.name = newName;
    }
}
   <console.log(me.name);   //accessing directly thru object output: Sina>
   <console.log(me.talk()); //accessed thru function, output: undefined. **Why undefined???????**>

    <me.setName("Reena");     //passing argument to setName()>
    <console.log(me.talk()); //output: Reena>

    <me.name = "Beena";       // can be changed name property directly like this?>
                        < //**if so, why not displaying Beeba instead of Reena?????**>
    <console.log(me.talk()); //**output: Reena not Beena. why???**>

Output:

Sina
undefined
Reena
Reena>
Biffen
  • 6,249
  • 6
  • 28
  • 36
Pooja
  • 17
  • 4

1 Answers1

0

Because you used arrow functions, but they don't have this.

So, if you change your code like here, it will work:

let me = {
name: "Sina",

talk: function() {
  return this.name;
},

setName: function(newName) {
    this.name = newName;
}
}

me.setName("Reena");
console.log(me.talk());

me.name = "Beena";
console.log(me.talk());

Try to learn more about arrow functions by reading this article: Arrow functions

Hope I helped you :)

Alexander
  • 24
  • 4