ThinkChat2.0新版上线,更智能更精彩,支持会话、画图、视频、阅读、搜索等,送10W Token,即刻开启你的AI之旅 广告
## js中对this关键字的理解 ### 1、在事件中,指向当前事件 ``` <input type="text" value="hello" id="test"> <script> var value = "change" var test = document.getElementById("test"); test.onclick = function () { go(); //在事件中,this指向正在执行事情的当前对象 console.log(this.value);//hello } //因函数是window的方法,故调用它的肯定是window中的value function go() { console.log(value);//change } </script> ``` ### 2、在构造函数中,指向当前实例化的对象 ``` <script> // es5 function Person(name,age){ this.name=name; this.age; } // es6 class Persons{ constructor(name,age){ this.name=name; this.age=age; } } var stu=new Person("quan",18) var stu1=new Persons("quan",18) console.log(stu.name) </script> ``` ### 在方法中,谁调用就指向谁 ``` 例1: var a = 2; var obj = { a : 1, foo : function(){ console.log(this.a); } } var f = obj.foo; f(); //2 obj.foo(); //1 例2: // function Person(name,age){ // this.name=name; // this.age; // } // Person.prototype.eat = function(name){ // console.log("这个方法是所有对象共有的,相当于N个对象公用一个eat方法"+ this.name); // }; // var stu = new Person("quan") // var ding = new Person("ding") // console.log(ding.eat()) // console.log(stu.eat()) ``` ## 实例:this的指向问题 ### 题目:给一个button按钮,点击使它变色,再点击,变回来。用三种方法。 #### tip:在事件中,指向当前事件 ``` 方法一: <button id="btn">点我</button> var btn=document.getElementById('btn'); btn.onclick=function(){ if(this.style.background=='red'){ this.style.background='' }else{ this.style.background="red" } 方法二:三元表达式 <button id="btn">点我</button> var btn=document.getElementById('btn'); btn.onclick=function(){ this.style.background=this.style.background=='red'?'':'red' } 方法三:用classlist <style> .one{ background-color: red; } </style> <button id="btn">点我</button> var btn=document.getElementById('btn'); btn.onclick=function(){ this.classList.toggle("one") } ``` ### tip:在构造函数中,指向当前实例化的对象 ``` class Person{ constructor(name,age){ this.name=name; this.age=age; } } var str=new Person("quan",18) ``` ### tip:在方法中,谁调用就指向谁 ``` var a=1; var obj={ a:2, go:function(){ console.log(this.a) } } obj.go();//2 obj.go.call()//1 //传参 var a=1; var obj={ a:2, go:function(b,c){ console.log(this.a+b+c) } } obj.go.call(window,'4','5')//145 obj.go.call(window,4,5)//10 ```