2

In ES5, other properties in object can be accessed by using this keyword. Same behavior but can't able to access other property in object by using this in arrow function (ES6)

Kindly run attached code snippet see the output

var person={
  "firstName":"PraveenRaj",
  "lastName":"D",
  "getFullName": function() { return this.firstName+" "+this.lastName}
}

var person1={
  "firstName":"PraveenRaj",
  "lastName":"D",
  "getFullName": () => this.firstName+" "+this.lastName
}

console.log(person.getFullName());
console.log(person1.getFullName());
Rishabh Maurya
  • 1,272
  • 3
  • 19
  • 37
praveenraj4ever
  • 349
  • 1
  • 4
  • 14
  • 2
    An arrow function expression has a shorter syntax than a function expression and does not have its own "this" [According to Docs](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions) – Dhaval Marthak Mar 01 '18 at 10:44
  • Yes, `this` behaves differently in arrow functions. That's their purpose. Don't use them when you don't want that. – Bergi Mar 01 '18 at 10:50
  • The same as ES6 arrow function can be achieved explicitly binding `this`: `"getFullName": function() { return this.firstName+" "+this.lastName}.bind(this)` – connexo Mar 01 '18 at 10:50

1 Answers1

0

Like all JavaScript variables, both the object name (which could be a normal variable) and the property name are case sensitive. You access the properties of an object with a simple dot-notation.

Following is the syntax for accessing Object Properties.

objectName.propertyName 

An arrow function expression has a shorter syntax than a function expression and does not have its own this, arguments, super, or new.target. These function expressions are best suited for non-method functions, and they cannot be used as constructors.

Credits: Docs, Reference Answer

Bits Please
  • 867
  • 5
  • 18