kujian / daily-interview-question

每日一道大厂前端面试题,每天半个小时学习,一年后会看到不一样的自己
81 stars 11 forks source link

第五题:说说call()、apply()、bind()的使用和区分? #9

Open kujian opened 5 years ago

kujian commented 5 years ago
var obj = {}//定义一个空的对象
function f(x,y){
console.log(x,y)
console.log(this) //this指向
}
ruochuan12 commented 5 years ago

刚好之前写过两篇文章,看完可以比较好的回答这个面试题 面试官问:能否模拟实现JS的bind方法 面试官问:能否模拟实现JS的call和apply方法

zxjzx commented 5 years ago

call,apply,bind的作用?

共同点:

举例

function fun(name,age){
    console.log(name,age);
    console.log(this)
}

let obj = {name:'jj',age:18};

fun('zz',12); // this指向window

fun.call(obj,'jj',18); //this指向obj
fun.apply(obj,['jj',18]); //this指向obj
fun.bind(obj)('jj',18); //this指向obj
ruochuan12 commented 5 years ago

@zxjzx callapply用法写反了~

zxjzx commented 5 years ago

@zxjzx callapply用法写反了~

thanks

xgqfrms commented 5 years ago

https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Function/call https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Function/apply