JS之 this用法

this

  1. 普通函数 window 调用者
console.log(this); //window
// this指向:

// 1、普通函数:window,调用者
function fn () {
	console.log(this);
}
fn(); //window
  1. 构造函数 实例化对象
function Perosn (uname, age) {
this.uname = uname;
this.age = age;
console.log(this);
}
let obj1 = new Perosn('阿飞', 22);
console.log(obj1);
let obj2 = new Perosn('李寻欢', 23);
console.log(obj2);
  1. 方法 调用者
let obj = {
uname : '张三丰',
age : 22,
fei : function () {
	console.log(this);
}
}
obj.fei();
  1. 事件处理函数 事件源
document.addEventListener('click', function () {
	console.log(this);
});  //#document
  1. 定时器 window调用者
window.setInterval(function () {
		console.log(this);
	}, 1000)
  1. 自调用函数 window调用者
;(function () {
		console.log(this);
	})()  //window

function fn () {
	console.log(this);
}

document.addEventListener('click', fn); //#document

动态指定普通函数中 this 的指向

  1. call
    使用call方法调用函数, 同时指定this的指向
    使用 call 方法调用函数时,第1个参数为 this 指定的值
    call 方法的其余参数会依次自动传入函数做为函数的参数
function fun (a, b) {
			console.log(this, a, b)
		}

let obj = {uname : '张三丰', age : 22};

// // call:
// // 函数.call(this,arg1, arg2,......)
// // 函数调用call、call会调用函数执行,在执行的过程中,改变this的指向
fun.call(obj, 1, 2);//Object 1 2
let obj = {
			uname : '张三丰',
			age : 22,
			fei : function () {
				console.log(this);
			}
		}
let o = {
		uname : '李寻欢',
		sex : '男'
	}
obj.fei.call(o); //指向对象o
  1. apply
    apply:函数.apply(this, [参数1, 参数2])
    apply 方法能够在调用函数的同时指定 this 的值
    使用 apply 方法调用函数时,第1个参数为 this 指定的值
    apply 方法第2个参数为数组,数组的单元值依次自动传入函数做为函数的参数
4. let obj = {
			uname : '张三丰',
			age : 22,
			taiji : function () {
				console.log(this);
			}
		}
		let o = {uname : '张无忌', age : 16};
		obj.taiji.apply(o); //this指向了o
5. // 数组:
		 let arr = [23, 66, 33, 19, 4, 7];
		 let re = Math.max.apply(null, arr);
		 console.log( re ); //66
6.    // ... rest参数:剩余参数,函数,解构赋值
		// ... 扩展运算符:数组,字符串,对象
		let arr = [23, 66, 33, 19, 4, 7];
		// ...扩展运算符
		let re = Math.max(...arr);
		console.log(re);//66
		
  1. Bind 方法不会调用函数,而是创建了一个指定了this值的新函数
    bind:函数.bind(this, arg1, arg2,…);
function fn (a, b) {
   		console.log(this, a, b);
   	}

   	let obj = {uname : '李寻欢', age : 22};

   	// let re = fn.bind(obj);re();
   	fn.bind(obj, 123, 456)();//Object 123 456


   	let btn = document.querySelector('input');

   	btn.addEventListener('click', function () {
   		// 禁用按钮
   		this.disabled = true;

   		// 开启定时器
   		setTimeout(function () {

   			this.disabled = false;

   		}.bind(this), 5000);

   	});

总结:

	// call:函数.call(this, arg1, arg2,......);
	// apply:函数.apply(this, [arg1, arg2,......])
	// bind:函数.bind(this, arg1, arg2,......)
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值