JavaScript Introducing ES2015 The Cooler Parts of ES2015 Arrow Functions

ella sherilyn ramos
ella sherilyn ramos
7,063 Points

What is the reason for assigning getKeys to another variable?

Hello,

I would just like to understand why we are trying to assign the getKeys to another variable? How is this relatable in real world problem?

And doing this returns the same set of keys.

'use strict';

var Person = function (data) {
  for (var key in data) {
    this[key] = data[key];  
  }
  this.getKeys = function () {
    return Object.keys(this);
  }
}

var Alena = new Person({ name: 'Alena', role: 'Teacher' });

console.log('Alena\'s Keys:', Alena.getKeys()); // 'this' refers to 'Alena'

var getKeys = Alena.getKeys();

console.log(getKeys); // 'this' refers to the node process

3 Answers

Steven Parker
Steven Parker
173,944 Points

The last 2 lines are a bit different in the video. They look like this instead:

var getKeys = Alena.getKeys;

console.log(getKeys()); // 'this' refers to the node process

As shown in the video, these produce different results.

ella sherilyn ramos
ella sherilyn ramos
7,063 Points

i know it has different lines of code. I just want to know why they did that. They could have provided a better example.

Steven Parker
Steven Parker
173,944 Points

The point of the demonstration is to show how "this" has different meanings when used in different contexts.

Libor Gess
Libor Gess
4,891 Points

I do not understand the purpose of the example. Why we just into oriental object programming?

Also why some people not answer question correctly? The question was simple 'why we are trying to assign the getKeys to another variable? How is this relatable in real world problem?'

The purpose of this example is to explain how anonymous functions and arrow functions work, is not focus on object-oriented programming. First, Object.keys() is a JavaScript method, please refer to this URL: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys This object receives an object as an argument, in the example we pass this as the argument to the function where this is the actual Person object (Elena). Now, when we assign Alena.getKeys to the getKeys variable the this scope out of the object and refers to the top-level code in a Node module, this is equivalent to module.exports. (that's because we run the file with node if we run it with chrome would be another story). With the arrow function, the function keeps referring to the object. That's the advantage of arrow function above anonymous functions which the teacher tries to explain.