Javascript
/
Classes
- 1 Fundamentals 11
-
Hello World S
-
Code structure S
-
Use strict S
-
Variables S
-
Data types S
-
Type conversions S
-
Maths S
-
Comparitions S
-
Conditional S
-
Loops S
-
Functions S
- 2 Testing 2
-
Mocha S
-
Nested describe S
- 3 Objects 4
-
Basics S
-
Reference S
-
Methods S
-
Constructor S
- 4 Types 5
-
Primitives S
-
Numbers S
-
Strings S
-
Arrays S
-
Json S
- 5 Classes 3
-
Constructor S
-
Binding S
-
Inheritance S
S
R
Q
Javascript Classes Binding
Losing this, problem solutions Wrapper function, method bind constructor this.click = this.click.bind(this) setTimeout () => button.focus(), 1000
Losing This
In another context, this won't be reference to its object any more.
/**
* Losing this, problem
*
* Javascrip this, depends on the context of the call
* In another context, it won't be reference to its object
*/
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.
/**
* Losing this, solutions
*
* Wrapper-function OR Bind the method
* The bind() method takes an object as an first argument
* and creates a new function
*/
class Button
{
constructor() {
this.click = this.click.bind(this); // method bind
}
click() {console.log("Click")}
focus() {console.log("Focus")}
blur = () => {console.log("Blur")} // wrapper-function
}
let button = new Button();
setTimeout(button.click, 1000); // Click
setTimeout(button.blur, 1000); // Blur
setTimeout(button.focus, 1000); // Blur
setTimeout(
() => button.focus(), 1000 // Focus
);
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