<!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>Document</title></head><body> <button id="btn" onclick="go()">btn</button> <script> /* 怎么理解函数内部this指向 tips: this取声明值,是在函数执行的时候确认,而不是在定义的时候确定 1 在普通函数中的this指向 */ function go(){ console.log(this); } go() </script></body></html>
<!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>Document</title></head><body> <button id="btn">btn</button> <script> var btn =document.getElementById("btn"); btn.onclick =function(){ setTimeout(function(){ console.log(this); },500) } </script></body></html>
<!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>Document</title></head><body> <script> // 4 call apply bind 函数关键字的指向 function fn1(){ console.log(this); } var obj ={ name:"vue" } fn1() fn1.call(obj); var fn2 =fn1.bind(obj); fn2(); </script></body></html>
<!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>Document</title></head><body> <script> // 2 作为对象的方法去调用 // 3 在箭头函数中this指向问题 var name =window var obj ={ name:"javascript", sayName(){ console.log(this.name); }, wait(){ setTimeout(function(){ console.log(this.name); }) }, delay(){ setTimeout(()=>{ console.log(this.name); }) }, layOUT(){ setTimeout(function(){ console.log(this.name); }.bind(this)) }, print(){ var that =this; setTimeout(function(){ console.log(this.name); }.bind(that)) } } obj.sayName() obj.wait() obj.delay() obj.layOUT() obj.print() </script></body></html>
<!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>Document</title></head><body> <!-- 5 class this 在class和构造函数中this指向new关键字实例化的对象 --> <script> class Person{ skill ="lisi"; constructor(name,age){ this.name =name; this.age =age; console.log(this); } } var p =new Person("lisi",18); console.log(p.name); </script></body></html>