Test start
Scenario:
- webpack: mode=development
- babel: babel/preset-env
- Arrow function
- In fact, it has nothing to do with Vue, but I encountered this disgusting problem in Vue
Question:
- Debugger process, real-time monitoring of this, and console Log (this) is inconsistent.
Simplified code:
const test1 = () => {
console.log('test1 called this------>', this);
};
const test2 = () => {
console.log('test2 called this------>', this);
test1();
};
test2();
Operation results:
Two window objects are output. It seems that there is no problem
However, at this time, break the two consoles, run them again, and press F10 to advance to the execution of test1 ()
Tragedy, watched aundefinedCome out.
Again, delete this in the console this time
Sure enough, there’s still one in the surveillanceundefined, enter this in the console, and then you can enter this in the consoleundefinedYes
End of test
Don’t you use this, it’s undefined; And using him, there is a point?
In fact, the JS running here is actually packaged by webpack and uses Babel compatibility. Let’s modify the code as follows:
class TClass {
a = 1;
b = 2;
c = 3;
constructor() {}
test1() {
console.log('test1 called this.a----->', this.a);
this.test2().then(() => {
debugger;
console.log('test1 called this.c----->', this.c);
});
}
test2() {
return new Promise((resolve, reject) => {
console.log('test2 called this.b----->', this.b);
resolve();
});
}
}
const tObject = new TClass();
tObject.test1();
Run it and monitor this at the debugger
This points to window?, Look at the console output
How did the properties of my class run to window??? No, just print it on the console
Speechless…. Since the running code is the code after Babel, it’s better to translate it on Babel’s official website
If I add one manually_thismonitor
I caught you
In fact, the processed JS is running, which makes debugging difficult. Fortunately, a solution has been found:
Use Babel plugin transform es2015 arrow functions dependency
npm i babel-plugin-transform-es2015-arrow-functions -D
After successful installation, it will be displayed in webpack.com config. JS or Babel config. Add this plug-in to JSON
module: {
rules: [
{
test: /\.m?js$/,
exclude: /(node_modules|bower_components)/,
use: {
loader: 'babel-loader',
options: {
presets: ['@babel/preset-env'],
plugins: [['transform-es2015-arrow-functions', { spec: true }]],
},
},
},
],
},
Let me Kangkang. What’s the change this time
Now the monitor, output, console, and mouse pointing to this can be identified correctly.
The problem was solved, but it was not completely solved.
Here is an article explaining that V8 optimization can also lead to this situation, but this is another situation
Why does Chrome debugger think closed local variable is undefined?
Baidu two hours is not as good as Google two minutes. (at first, I thought my problem was here, but I found that I saw the wrong direction)
epilogue
JS awesome.