MIguel Barra
MIguel Barra

Reputation: 21

Why a function is treated as a class in JavaScript

I'm on "Introducing ES2015" course of Treehouse and the teacher shows this code to illustrate the arrow functions but here he instantiates the function as a class. Can anybody tell me how is it possible?

What I learned about objects is that you need to create a class before to instantiate it or create a literal object which is not this case.

'use strict';

var Person = function(data) {
    for (var key in data) {
        this[key] = data[key];
    }
    this.getKeys = () => {
        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());

Everything works but I don't know why.

Upvotes: 2

Views: 887

Answers (1)

Jonas Wilms
Jonas Wilms

Reputation: 138267

You should ask yourself one question: What is a class really?

Actually it is just a syntax to compose the following things:

1) A constructor. That is some kind of function, that constructs an instance of the class.

2) methods. They can be called on instances.

Now for the second one, JS has already a great feature to achieve this: Prototypal Inheritance. Objects can inherit other objects, including methods:

  const proto = { method() { /*...*/ } };

  const instance = Object.create(proto);
  instance.method(); // that works, as instance inherits proto

Now we only need constructors, for that we could just call a function after we created an object using the method above:

   constructInstance(Object.create(proto));

Now as that is quite a common task (as JS has prototypal inheritance from the beginning), the new operator was added, which basically does all that:

1) It creates an empty object inheriting from .prototype of the function called on.

2) It calls the function itself with this being the object.

3) It gives back that object.

   function Person(name) {
     this.name = name;
   }

   Person.prototype.method = function() { /*...*/ };

  new Person("Jonas").method();

And there you go, inheritance & constructors without any classes.

Now as that is still no quite beautiful, the class syntax was added, which basically just creates a function with a prototype.

Upvotes: 2

Related Questions