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
)
Run codeHide resultfunction A() {
if (!this instanceof A) {
throw new TypeError("Class constructor A cannot be invoked without 'new'");
}
this.something = 5;
}
console.log(
new A().something
)
Run codeHide resultthisnot 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()
Hide resultnew, , this new.
( ), .
, , .. new A(), JavaScript ( A):
function A() {
var newObjectThatWillBeThis = {};
newObjectThatWillBeThis.something = 5;
return newObjectThatWillBeThis;
}
OLOO , . answer by getify, OLOO, .