call 和 apply ,bind之间的区别
- call 和 apply,bind都是改变this,但是call,是改变this指向,但是传参的形式是一个一个的传,而apply的传参的形式是以数组的形式传入。bind传参的形式也是一个一个传,但是bind是只绑定作用域,不执行函数,明白了其各自的特点就可以手写call,apply和bind的了
- 手写 call 方法
var h = {
name:'Tim',
fn:function(a,b){
console.log(a +b)
}
}
var b = h.fn;
b.call(h,1,2)
Function.prototype.myCall = function(xhr){
xhr = xhr || window;
xhr.fn = this
let arg = [...arguments].slice(1);
let result = xhr.fn(...arg)
}
b.myCall(h,1,2)
- 手写bind
Function.prototype.myBind = function(xhr){
xhr = xhr || window;
xhr.fn = this
let arg = [...arguments].slice(1);
function result(){
xhr.fn(...arg)
}
return result
}
- 手写apply
Function.prototype.myApply = function(xhr){
xhr = xhr || window
xhr.fn = this // xhr.fn = this this = 调用的函数
// 取得实参中的除第一位以外的数
let arg = [...arguments].slice(1)
xhr.fn(...arg[0])
}