前端this指向问题解决方案bind
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>前端this指向问题普通函数</title> </head> <body> <script> //口诀 谁调用就会指向谁 这边是普通函数 直接报错this.fang is not a function var name="geyao" var fangfang = { name : "fangfang", fang: function () { console.log(this.name) }, fun: function () { setTimeout( function () this.fang() }.bind(fangfang)(),100); } }; fangfang.fun() </script> </body> </html>
前端this指向问题解决方案call
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>前端this指向问题普通函数</title> </head> <body> <script> //口诀 谁调用就会指向谁 这边是普通函数 直接报错this.fang is not a function var name="geyao" var fangfang = { name : "fangfang", fang: function () { console.log(this.name) }, fun: function () { setTimeout( function () { this.fang() }.call(this,fangfang),100); } }; fangfang.fun() </script> </body> </html>
前端this指向问题解决方案this
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>前端this指向问题普通函数</title> </head> <body> <script> //口诀 谁调用就会指向谁 这边是普通函数 直接报错this.fang is not a function var name="geyao" var fangfang = { name : "fangfang", fang: function () { console.log(this.name) }, fun: function () { _this=this setTimeout( function () { _this.fang() },100); } }; fangfang.fun() </script> </body> </html>
前端this指向问题解决方案箭头函数
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>前端this指向问题普通函数</title> </head> <body> <script> //口诀 谁调用就会指向谁 这边是普通函数 直接报错this.fang is not a function var name = "geyao" var fangfang = { name: "fangfang", fang: function () { console.log(this.name) }, fun: function () { setTimeout(() => { this.fang() }, 100); } }; fangfang.fun() </script> </body> </html>