What does the value of 'this' mean in es6 classes

I am currently studying prototype inheritance in JavaScript. From what I have read so far, in es5, the keyword thisrefers to the context from which the function is being called.

However, with ES6 classes, I read that the value of 'this' is lexically related to an instance of the class. Can someone explain this to me? On a side note. I also read that I should not use class syntax, but instead use the OLOO pattern. Edit: I wanted to ask a question here. Eric Elliot seems adamant not to approach wop and inheritance in this way, but to use his OLOO image instead. He is right? Or is his opinion full of fluff?

+4
source share
1 answer

Adding classes to ES6 does not change the binding rules this. In fact, ES6 classes are just syntactic sugar on top of regular prototype inheritance.

Classes simply add some security checks under the hood and allow simpler syntax.

The following two examples are essentially equivalent:

class A {
  constructor() {
    this.something = 5;
  }
}

console.log(
  new A().something // 5
)
Run codeHide result

function A() {
  if (!this instanceof A) {
    throw new TypeError("Class constructor A cannot be invoked without 'new'");
  }
  this.something = 5;
}

console.log(
  new A().something // 5
)
Run codeHide result

thisnot relevant to the context from which the function is called. In most cases, the value thisis determined by how the function is called.

, , .. this instanceof A, , A new . .

class A {
  constructor() {
    this.something = 5;
  }
}

A() // Error!
Hide result

new, , this new.

( ), .

, , .. new A(), JavaScript ( A):

function A() {
  var newObjectThatWillBeThis = {};
  newObjectThatWillBeThis.something = 5;
  return newObjectThatWillBeThis;
}

OLOO , . answer by getify, OLOO, .

+4

Source: https://habr.com/ru/post/1665673/


All Articles