prompt
This article will only talk about the pre-knowledge of this, not in-depth. I’ll tell you why you need this first. Learn to know why!!
About this
The this keyword is one of the most complex mechanisms in JS. It’s a very special thing, defined in all functions. Even very experienced JS developers have a hard time figuring out what it points to. Any advanced technology is indistinguishable from magic.
Today we begin to unravel its mysteries.
Why this
function identify() {
return this.name.toUpperCase()
}
function speak() {
const greeting = 'Hello, I am ' + identify.call(this);
console.log(greeting)
}
var me = {
name: 'MaPaoPao'
}
var you = {
name: 'XiaoMing'
}
identify.call(me) // MAPAOPAO
identify.call(you) // XIAOMING
speak.call(me) // Hello, I am MAPAOPAO
speak.call(you) // Hello, I am XIAOMING
Copy the code
As you can see, with this, all we need to do is make sure that this executes when we call the function, and the code inside the function is pretty clean. What to do without this:
unction identify(context) {
return context.name.toUpperCase()
}
function speak(context) {
const greeting = 'Hello, I am ' + identify(context);
console.log(greeting)
}
var me = {
name: 'MaPaoPao'
}
var you = {
name: 'XiaoMing'
}
console.log(identify(you))
speak(me)
Copy the code
The objects to be used have to be passed into the function as arguments, and the more arguments a function has, the more complex the code structure becomes.
As usage scenarios become more complex, displaying passing context objects can mess up your code. This provides a more elegant way to implicitly ‘pass’ an object, so the API can be designed to be cleaner and easier to reuse.
Misunderstanding of this
To self?
Executes the code, foo executes it three times, and 2 prints it three times. And foo.count is still 1. Prove that this does not refer to Foo itself.
function foo() {
console.log(2) / / 2 2 2
this.count++;
}
foo.count = 1;
foo();
foo();
foo();
console.log(foo.count) / / 1
Copy the code
Point to the scope of the function?
Although it may be true in some cases, this statement is still false.
This code attempts to connect foo and bar’s static scope through this, so that bar can use variables in Foo’s scope, which obviously cannot be done.
function foo() {
var a = 2;
this.bar();
}
function bar() {
console.log(this.a);
}
foo() // a is not defined
Copy the code
What is this
This film introduces the use of this and some misunderstandings of this, in order to deepen readers’ understanding. In the next part, we will explain this clearly. The end starts with the idea that this is actually the binding that happens when the function is called, and that it points to depending on where the function is called.
Related articles
The next article you don’t know js – this full analysis