概念
在javascript中this指的就是对象的指向。
应用场景
1、普通对象中的this
var obj = {
name:'rise',
showMess () {
//this 指向当前obj对象
}
}
2、全局环境下this
this === window
//true this就是window
3、普通函数中this
function getMess(){
console.log(this)
}
getMess()
调用普通函数this也是指向window
//VM440:2 Window {postMessage: ƒ, blur: ƒ, focus: ƒ, close: ƒ, parent: Window, …}
4.dom选择器中的this
var dom = document.body;
dom.onclick = function(){
console.log(this)
}
//this是dom元素
//<body>...</body>
5.jquery选择器中this
$('div').on('click',function(){
console.log(this)
})
//this 指向jquery选择器对象
this的绑定
- 默认绑定
- new绑定
隐式绑定
在一个对象的内部通过属性间接引用函数,从而把this隐式绑定到对象内部属性所指向的函数(例如上例中的对象parent的child属性引用函数function child(){} 。显示绑定
需要引用一个对象时进行强制绑定调用,js有提供call()、apply()方法,ES5中也提供了内置的方法Function.prototype.bind
。
默认绑定
非严格模式下,在浏览器window全局对象下会将a绑定到window.a
function demo(){
console.log(this.a); // 1
}
let a = 1;
demo();
严格模式下调用
'use strict'
function demo(){
console.log(this.a); // TypeError: Cannot read property 'a' of undefined
}
const a = 1;
demo();
//VM277:4 Uncaught TypeError: Cannot read property 'a' of undefined
at demo (<anonymous>:4:22)
at <anonymous>:9:1
new绑定
也是一种可以影响this调用的方法,需要清楚new绑定,它是一个构造函数,每一次new绑定都会初始化新创建的对象。
function fruit(name){
console.log(name, this);
}
const f1 = new fruit('apple'); // apple fruit {}
显示绑定
function fruit(){
console.log(this.name);
}
var apple = {
name: '苹果'
}
fruit = fruit.bind(apple);
fruit(); // 苹果 这里借助bind将this指向了apple对象
隐示绑定
var name = "rise"
var obj = {
name:'kitt',
show(){
console.log(this.name)
}
}
var show2 = obj.show
show2()
//这段代码执行结果是rise
//obj.show()执行结果是kitt
//总结 var show2 = obj.show 这段代码 此时环境是在window环境下 show2()下的this是window
this绑定优先级
- new绑定
- 显示绑定
- 隐式绑定
- 默认绑定(严格模式下会绑定到undefined)