Home > Article > Web Front-end > Some little knowledge about this keyword in Javascript_javascript skills
Javascript should be one of the most popular cross-platform languages now. I have been playing with some interesting things on the front end, but I found that I have not mastered this language well. It's a bit of a waste of time, so I want to take advantage of the free time now to add some missing things.
Implicit binding of this
This was something that confused me at first. When I first saw it, I didn’t understand it. Then, in similar situations, similar methods can be used to solve the same problem. So I tried to sort out the knowledge and make it easier to find.
This is a design error in the Javascript language, but it seems that this error is inevitable. Functions are objects, arrays are objects, etc. Quoting examples from "Javascript: The Good Parts"
The result of sum at this time is 7.
When calling a function in this mode, this is bound to a global variable.
That is, in the current environment, we can call this
like this
};
console.log(user.hello());
If we define a variable in this method and assign it the value this, then the internal function can access this through that variable.
var that = this
So when the situation is a little more complicated, we need to use:
1.The scope of this variable is always determined by its nearest enclosing function.
2. Use a local variable (such as me, self, that) to make this binding available internally.
A simple example:
var MM = function(){
z = new M();
This.name = "MM";
z.printName = function(){
console.log(this.name);
};
Return z.printName();
};
var mm = new MM;
This will return a MM. In addition, in ES5 you can use the bind method of the callback function.
Others
Another hello, world
I encountered print('Hello')('World') by chance, and then output 'Hello, World'.
The so-called higher-order functions seem to be very useful. If you are interested, you can read the next article.