1

It should have referred to parent as it is not dependent on calling //context and takes lexical scope (I am taking greeting(); it is taking window).

Below is the example

    var Person = {
      name: "Tim",
      age: 28,
      greeting:()=>{
        console.log("Hello " + this.name + ".  Wow, you are " + this.age + " years old.");
    }
    }
    Person.greeting()
    var greeting = Person.greeting;
    greeting(); 
    <!DOCTYPE html>
    <html>
    <>
    
    <h1>Hello World!</h1>
    
marc_s
  • 675,133
  • 158
  • 1,253
  • 1,388
  • 1
    Where is your arrow function? – Krishna Prashatt Feb 19 '19 at 05:43
  • I don't see an arrow function there.. Did you miss something? Use [edit] option to explain – Suraj Rao Feb 19 '19 at 05:44
  • I think his "arrow" function is referring to the `greeting: function(){ .. }` – Samleo Feb 19 '19 at 05:45
  • Arrow functions doesn't contains "this" and "arguments" object by default. If user uses arrow functions then that used "this" object refers to the "this" outside the arrow function's scope. – RK_15 Feb 19 '19 at 06:10
  • Hello I have updated code please check. – Saurabh Joshi Feb 19 '19 at 06:55
  • @RK_15 In this case arrow function should have referred to person object instead of window? – Saurabh Joshi Feb 19 '19 at 06:56
  • @saurabh joshi - I am talking about outer function’s scope. If arrow function is contained inside another function then that function’s this object will be inherited by arrow function. There are only two scopes in JS, (global scope and local scope) there is nothing called object scope is there in JS. – RK_15 Feb 19 '19 at 07:14
  • @SaurabhJoshi You can refer to following [fiddle](https://jsfiddle.net/RajeshDixit/q4jo8dne/11/). I have added explanation and example. Hope it helps! – Rajesh Feb 19 '19 at 07:17

1 Answers1

0

Arrow functions do not have their own this.

An arrow function expression is a syntactically compact alternative to a regular function expression, although without its own bindings to the this, arguments, super, or new.target keywords.

You can bind() the object with normal function syntax:

var Person = {
  name: "Tim",
  age: 28,
  greeting:function(){
    console.log("Hello " + this.name + ".  Wow, you are " + this.age + " years old.");
  }
}
Person.greeting()
var greeting = Person.greeting.bind(Person);
greeting();
Mamun
  • 58,653
  • 9
  • 33
  • 46