javascript中的this绑定

this是一个关键字,表示执行当前函数的对象

  • this永远跟着当前函数走,
  • 永远是一个对象,
  • 永远在函数执行时才能确定。

1. 默认绑定:没有明确被隶属对象执行的函数,this指向window

function fn(){
	console.log(this);				//window
	console.log(typeof this);		//object
}
fn();

- 严格模式下,this指向undefiend

"use strict";
function fn(){
	console.log(this);				//undefined
}
fn();

2. 隐式绑定:明确被隶属对象执行的函数,this指向执行对象

var obj = {
	fn:function(){
		console.log(this);
	}
}
obj.fn();							//this指向obj

- 隐式丢失:某函数被当做参数传递给另一个函数,则会丢失原本的执行对象,指向window

var obj = {
	fn:function(){
		console.log(this);
	}
}
function test(cb){
    cb();
}
test(obj.fn);					//this指向window

- 注意:不是所有的回调函数中this都指向window,某些特定情况下被系统修改了。

document.addEventListener("click",function(){
    console.log(this);            //this指向document
});

3. 显示绑定(强制绑定):利用函数的方法改变this的指向(解决了this隐式丢失的问题)

例1:

function fn(a){
    console.log(this);
    console.log(typeof this);	//object
}
fn.call("hello");				//this指向hello

例2:针对上方隐式绑定的隐式丢失问题,可以这样解决

var obj = {
	fn:function(){
		console.log(this);
	}
}
function test(cb){
  cb.call(obj);					//this指向obj
}
test(obj.fn);

4. new绑定:函数被new执行后,函数内部的this指向new出的实例

function Fn(){
	console.log(this);
	console.log(typeof this);	//object
}
new Fn();						//this指向Fn{}
  • 8
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值