call
改变 this指向
function test(){
}
test()// 调用函数 等同于 test.call()
传参 this指向 第一个参数(对象)
var obj = {
name:'obj',
obb:function(age){
console.log(this.name,age)
}
}
var obj2 = {
name:"obj2"
}
obj.obb(2);// 'obj' 2
obj.obb.call();// undefined ??
obj.obb.call(2);// undefined undefined??
obj.obb.call(obj2,2); //"obj2" 2
借别人的方法来构造自己的函数
function Per(name,age){
this.name = name;
this.age = age;
}
var obj = {}
Per.call(obj,'obj',18);
console.log(obj);//{name: "obj", age: 18}
function Per(name,age){
this.name = name;
this.age = age;
}
function Stu(name,age,sex,tel){
// this = {}
Per.call(this,name,age)
// this = {name:'',age:''}
this.sex = sex;
this.tel = tel;
}
var stu = new Stu('stu',18,'male',110);
console.log(stu);//{name: "stu", age: 18, sex: "male", tel: 110}
apply
改变 this指向
apply和call区别 传参列表不同
this 是对象
call 需要把实参按照形参的个数传进去 (this,x1,x2,…)
apply 需要传一个 实参数组arguments (this,arguments)
function Per(name,age){
this.name = name;
this.age = age;
}
var obj = {}
Per.apply(obj,['name',18])
console.log(obj);//{name: "name", age: 18}
call/apply 封装实现
Function.prototype.myCall = function(target=window,...args){
if (typeof this !== "function") throw new Error('type error')
var fun = Symbol()
target[fun] = this
const val = target[fun](...args)
delete target[fun]
return val
}
Function.prototype.myApply = function(target=window,arr){
if (typeof this !== "function") throw new Error('type error')
target.fun = this
const val = target.fun(...arr)
delete target.fun
return val
}