多应用+插件架构,代码干净,二开方便,首家独创一键云编译技术,文档视频完善,免费商用码云13.8K 广告
1. 哪个函数使用this this就指向当前 ~~~ <input type="button" value="hello" id="test"> <script> var value = "change" var test = document.getElementById("test"); test.onclick = function(){ go(); } function go(){ console.log(this.value); } ~~~ 2. setTimeout 是window的事件 this指向window ~~~ <input type="button" value="hello" id="test"> <script> var value = "change" var test = document.getElementById("test"); test.onclick = function(){ setTimeout(function(){ console.log(this.value); //change },300) //this还是指向window-->函数正常调用,this指向window } ~~~ 3. 箭头函数解决this指向问题 ~~~ <input type="button" value="hello" id="test"> <script> var value = "change" var test = document.getElementById("test"); test.onclick = function(){ setTimeout(()=>{ console.log(this.value); },300) } </script> ~~~ 4. bind 解决this指向问题 ~~~ <input type="button" value="hello" id="test"> <script> var value = "change" var test = document.getElementById("test"); test.onclick = function(){ setTimeout(function(){ console.log(this.value); //hello }.bind(this),300) } </script> ~~~ 5. 定义变量装载this ~~~ <input type="button" value="hello" id="test"> <script> var value = "change" var test = document.getElementById("test"); test.onclick = function(){ var self = this setTimeout(function(){ console.log(self.value); //hello },300) } </script> ~~~ 6. call-->改变函数内部this,关键字的指向 call(thisObj,params) ~~~ var cheng={ name:"cheng" } var jiang = { name:"jiang", sayName(a,b){ console.log(this.name); console.log(a+b); } } jiang.sayName.call(cheng,1,2); ~~~ 7. apply-->改变函数内部this关键字的指向 apply(thisObj,[params]) ~~~ var cheng={ name:"cheng" } var jiang = { name:"jiang", sayName(a,b){ console.log(this.name); console.log(a+b); } } jiang.sayName.apply(cheng,[1,2]) ~~~ 6. call-->改变函数内部this,关键字的指向 call(thisObj,params) ~~~ ~~~ this在函数和事件中的指向以及改变方法 ~~~ <input type="text" value="童" id="input"> <script> // var input =document.getElementById("input"); // var value="wang" // input.onclick=function(){ // console.log(this.value) // } // input.onclick.apply() // var name="tong" // var obj={ // name:"wang", // age:18, // sayname:function(){ // console.log(this.name) // } // } // obj.sayname.apply() </script> ~~~ 在构造函数中this的指向以及改变方式 ~~~ <!-- bind,call,apply只能通过跟着函数(不能使用方法)来改变this,bind要使用在函数本身 其他的是在调用的时候--> <script> var obj={ name:"童" } class person{ constructor(name,age){ this.name = name; this.age = age; // this.sayname=function(){ // console.log(this.name) // } } sayname(){ console.log(this.name) } } var stu =new person("tong") stu.sayname.call(obj); // function fn(name){ // this.name=name; // this.fn1=function(){ // console.log(this.name); // } // }; // var obj={}; // // fn.call(obj,'jack'); // fn.apply(obj,['jack']); // console.log(obj.name); // obj.fn1(); </script> ~~~ ~~~ var name = "li"; var cheng = { name: "cheng", test() { console.log(this.name) } } // cheng.test.bind()() // console.log(typeof(cheng)) // var a = cheng.test.bind() // a() // cheng.test.call(); // cheng.test.apply() ~~~