Javascript
/
Classes
- 1 Fundamentals 11
-
Hello World
-
Code structure
-
Use strict
-
Variables
-
Data types
-
Type conversions
-
Maths
-
Comparitions
-
Conditional
-
Loops
-
Functions
- 2 Testing 2
-
Mocha
-
Nested describe
- 3 Objects 4
-
Basics
-
Reference
-
Methods
-
Constructor
- 4 Types 5
-
Primitives
-
Numbers
-
Strings
-
Arrays
-
Json
- 5 Classes 3
-
Constructor
-
Binding
-
Inheritance
/
Binding
➟
➟
Last update: 27-01-2022
This
An object method could be passed around and called in another context.
/**
* JavaScript this depends on the context of the call.
*
* In another context, 'this' won't be reference to its object any more.
*
* The problem is called 'losing this'.
*/
class Button
{
constructor(value) {
this.value = value;
}
click() {
console.log(this.value);
}
}
let button = new Button("hello");
setTimeout(button.click, 1000); // undefined
Bind
We might need to bind the method to object.
/**
* Method binding:
*
* There are two ways of fixing 'losing this' problem:
*
* Pass a wrapper-function or ...
* Bind the method to object in constructor.
*
* The bind() method takes an object as an first argument
* and creates a new function.
*/
/**
* First example
*/
class Button
{
constructor() {
this.click = this.click.bind(this); // method bind
}
click() {
console.log("Click");
}
blur = () => {
console.log("Blur"); // wrapper-function
}
focus() {
console.log("Focus");
}
}
let button = new Button();
setTimeout(button.click, 1000); // Click
setTimeout(button.blur, 1000); // Blur
setTimeout(
() => button.focus(), 1000 // Focus
);
/**
* Second example
*/
class User {
getName() {
return this.name;
}
}
let obj = new User();
let user1 = {name: "John"};
let user2 = {name: "Ana"};
console.log(obj.getName()); // undefiend
console.log(obj.getName.bind(user1)()); // John
console.log(obj.getName.bind(user2)()); // Ana
➥ Questions github Classes