The “this” line refers to the problem
var name = "windowsName";
function func1(){
console.log('windows func1')}var a = {
name: 'test'.func1: function() {
console.log('a.func1')
console.log(this.name)
},
func2: function(){
setTimeout(function(){
this.func1()
}, 100)}}; a.func2()// The output is Windows func1
Copy the code
The output shows that the setTimeout object is a window, so the output looks like this.
Use _this = this inside the function
var name = "windowsName";
function func1(){
console.log('windows func1')}var a = {
name: 'test'.func1: function() {
console.log('a.func1')
console.log(this.name)
},
func2: function(){
let _this = this;
setTimeout(function(){
_this.func1()
}, 100)}}; a.func2()// The output is a.unc1
Copy the code
Using the arrow function
To quote MDN, arrow functions do not create their own ‘this’; they only inherit this from the upper level of their scope chain
var name = "windowsName";
function func1(){
console.log('windows func1')}var a = {
name: 'test'.func1: function() {
console.log('a.func1')
console.log(this.name)
},
func2: function(){
setTimeout(() = > {
this.func1()
}, 100)}}; a.func2()// The output is a.unc1
Copy the code
Use apply Call Bind
Use the apply
var name = "windowsName";
function func1(){
console.log('windows func1')}var a = {
name: 'test'.func1: function() {
console.log('a.func1')
console.log(this.name)
},
func2: function(){
setTimeout(() = > {
this.func1()
}.bind(a), 100)}}; a.func2()// The output is a.unc1
Copy the code
Use the call
var name = "windowsName";
function func1(){
console.log('windows func1')}var a = {
name: 'test'.func1: function() {
console.log('a.func1')
console.log(this.name)
},
func2: function(){
setTimeout(() = > {
this.func1()
}.call(a), 100)}}; a.func2()// The output is a.unc1
Copy the code
Use the bind
var name = "windowsName";
function func1(){
console.log('windows func1')}var a = {
name: 'test'.func1: function() {
console.log('a.func1')
console.log(this.name)
},
func2: function(){
setTimeout(() = > {
this.func1()
}.bind(a)(), 100)}}; a.func2()// The output is a.unc1
Copy the code