前言
this是Javascript语言的一个关键字它代表函数运行时,自动生成的一个内部对象,只能在函数内部使用。
this指向十分重要,了解js中this指向是每一个学习js的人必学的知识点。这些是我在学习中借鉴前人总结的,希望对你有用。
常见的几种 this 指向场景
-
全局作用域或者普通函数中 this 指向全局对象window。
//直接打印 console.log(this) //window //function声明函数 function bar () { console.log(this) } bar() //window 严格模式下输出 undefined //function声明函数赋给变量 var bar = function () { console.log(this) } bar() //window 严格模式下输出 undefined //自执行函数 ( function () { console.log(this) } )(); //window 严格模式下输出 undefined
-
方法调用中调用的 this 指向
//对象方法调用 var person = { run: function () {console.log(this)} } person.run() // person //事件绑定 var btn = document.querySelector("button") btn.onclick = function () { console.log(this) // btn } //事件监听 var btn = document.querySelector("button") btn.addEventListener('click', function () { console.log(this) //btn }) //jquery的ajax $.ajax({ self: this, ··· success: function (res) { console.log(this) // this指向传入$.ajxa()中的对象 console.log(self) // window }
}); //这里说明以下,将代码简写为$.ajax(obj) ,this指向obj,在obj中this指向window,因为在在success方法中,独享obj调用自己,所以this指向obj ```
-
在构造函数或者构造函数原型对象中的 this 指向构造函数的实例
//不使用new指向window function Person (name) { console.log(this) // window this.name = name; } Person('inwe') //使用new function Person (name) { this.name = name console.log(this) //people self = this } var people = new Person('iwen') console.log(self === people) //true //这里new改变了this指向,将this由window指向Person的实例对象people
-
函数体中,return新的函数的 this 指向
//常见问题 var myObj={ name:'myObject', toString:function(){ return `this ${ this.name ? this.name : this }` }, getInfo:function(){ return (function(){ return this.toString(); // 内部 匿名函数自调用,因此this指向了全局对象 window })(); } } alert(myObj.getInfo()); // 报错 this 指向window 而window并有 toString 函数还怎么调用。 严格模式下this 为 undefined //解决办法 var myObj={ name:'myObject', toString:function() { return `this ${ this.name ? this.name : this }` }, getInfo:function(){ var This=this;//先把当前的this指向存起来 return (function(){ return This.toString(); })(); } } alert(myObj.getInfo()); // this myObject
总结
此学习篇,主要列举了一些应用场景的this指向问题。
并未总结改变this指向的 bing call applay方法。
本人菜鸟一枚,文中若有错误,希望大神们能帮忙指出,指点指点。