0
let objNewWay = {
  width:400,
  height:300,
  area: () => this.width*this.height
};

console.log(objNewWay.area()); // NaN

let objOldWay = {
  width:400,
  height:300,
  area: function() {
    return this.width*this.height;
  }
};

console.log(objOldWay.area()); // 120000

I don't understand why the arrow function in Javascript object does not seems to work. If you look at the code above, the first console.log prints NaN, and the second prints the number as expected.

https://jsbin.com/pazazikayi/edit?js,console

  • 2
    Its called [Arrow functions](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions) not lamda – Satpal Apr 19 '17 at 08:50
  • From _MDN_: ___Two factors influenced the introduction of arrow functions: shorter functions and non-binding of `this`.___ – Rayon Apr 19 '17 at 08:50
  • Thanks. I have changed the question from lambda to array function. –  Apr 19 '17 at 08:53
  • 1
    **arrow** function, not *array* function. – Felix Kling Apr 19 '17 at 13:30

2 Answers2

5

From the documentation :

An arrow function expression has a shorter syntax than a function expression and does not bind 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.

You have to use the old way like you already showed

area: function() {
   return this.width*this.height;
}

if you still want to use the arrow function, you have to call the object itself

let objNewWay = {
  width:400,
  height:300,
  area: ()=> objNewWay.width*objNewWay.height
};

console.log(objNewWay.area()); // NaN
Weedoze
  • 13,683
  • 1
  • 33
  • 63
1

The arrow functions are not lambdas, and the way you use it will refer to a different scope from your object's.

For instance, from the console:

let theObj = {
    whereAmI: () => console.log(this)
}

theObj.whereAmI();

// Window...

If you want to use this keyword, use to the area: function(){} way.

dashdashzako
  • 1,268
  • 15
  • 24