JavaScript Call, Bind, Apply

Call, Bind, Apply 这些方法可以让你去指定绑定的 this

如果没有绑定this的话,下面的this指的是 window 物件

function aa(){
console.log(this);
console.log(this.name);
}
aa();

//Window {0: Window, window: Window, self: Window, document: document, name: '', location: //Location, …}

那麽现在来介绍能指定绑定this 的三个方法吧!

Bind 绑定某物件,让 this 指向该物件(不过会回传function)

function aa(){
console.log(this);
console.log(this.name);
}

let st={
name:'Ivy',
age:20
}
//注意,ff是函数
let ff=aa.bind(st);
ff();
//{name: 'Ivy', age: 20}
//Ivy

Call (与Bind 很像,不过不会回传函数)

Untitled

**如果此函数有其他参数就写在call的物件後面

function aa(good){
console.log(this);
console.log(this.name);
console.log(good);
}

let st={
name:'Ivy',
age:20}

aa.call(st,'444666');
//{name: 'Ivy', age: 20}
//Ivy
//444666

Apply 与 Call 很像,只是传入的会包成阵列

function aa(good,jj){
console.log(this);
console.log(this.name);
console.log(good);
console.log(jj);
}

let st={
	name:'Ivy',
	age:20}
    
// 要传入的参数用阵列包起来,放在要apply的物件後面
aa.apply(st,['444666',1111111]);
//{name: 'Ivy', age: 20}
// Ivy
// 444666
// 1111111

小测试:

1.哪个方法的参数要用阵列包装?
2.哪个方法绑定时是回传函数?

参考资料:
Runoob.com JavaScript 中 call()、apply()、bind() 的用法
MDN Function.prototype.call


<<:  [Day 20] 看看看的监听器watch

>>:  D19 - 今晚我想来点 唯独派 getter 唯写派 setter

[Day 12] 当冲实验结果概述

一、总结 总结来说,今天研究了一整天论文, 该篇论文对蒐集5分线数据,并以此预测之後的股价倾向, 与...

D00 - 缘起

大家好我是鳕鱼,历年来看了很多届铁人赛,今年终於鼓起勇气填坑参赛了。 回想自身技术发展历程,还真的是...

【CSS】【Bootstrap】关於order

【前言】 本系列为个人前端学习之路的学习笔记,在过往的学习过程中累积了很多笔记,如今想藉着IT邦帮忙...

Best Notched SAA-C02 PDF Dumps of CertsQuestions - Hassle no cost results

Passing Amazon SAA-C02 certification exam with min...

Day 30:Google Map 结合口罩资料 & 铁人赛最後一天

本篇文章同步发表在 HKT 线上教室 部落格,线上影音教学课程已上架至 Udemy 和 Youtu...