1. 手写实现call函数
var person ={
getName:function(){
console.log(this) //window
return this.name
}
}
var man={
name:'张三'
}
console.log(person.getName) // undefined
console.log(person.getName.call(man)) //张三
//------------------------------------------
//手写call函数--简写
Function.prototype.call=function(context){
//1. getName函数要执行
//1-2 这个时候 getName的函数里 this指向的是window
//1-3 传过来的context参数是需要指向的man对象
context.fn=this //这里的this是getName函数,因为是getName来调用的call。然后
//把这个this赋值给context对象上的fn函数,所以现在就是传入的参数在调用getName函数
return context.fn() //2. 返回调用后的结果
}
console.log(person.getName.call(man))
//详细写
Function.prototype.call = function (context) {
//对this进行类型判断,如果不是function类型,就报错
//this应该指向的是调用call函数的对象(function也属于对象object类型)
if (typeof this !== 'function') {
throw new Error('this is not a funtion')
}
//形参不一定会传
//不传的话,默认是window
context = context || window
//取参数
const args = [...arguments].slice(1)
// 假如context上面有fn属性的时候,会出现冲突
// 所以当context上面有fn属性的时候,要先保存一下
var temp = null
if (context.fn) {
temp = context.fn
}
// 给context创建一个fn属性,并将值设置为需要调用的函数(即this)
context.fn = this
const res = context.fn(args)
// 删除context对象上的fn属性
if (temp) {
context.fn = temp
} else {
delete context.fn
}
// 返回运行结果
return res
}
视频参考地址:
apply bind 方法的手写:
2. call apply 的应用场景
1. js的继承,使用call+构造函数实现继承
2. 判断js 的数据类型
3. 把伪数组转为数组
//继承
//构造函数大写开头以区分,不需要return
function Animal() {
this.eat = function(){
console.log("吃东西")
}
}
function Bird() {
this.fly = function() {
console.log("我会飞")
}
}
function Cat() {
//使用cat的this调用Animal/Bird Animal/Bird中的this也变成cat 所以可以调用
Animal.call(this);
Bird.call(this)
this.sayName = function(){
console.log("输出自己的名字")
}
}
let cat = new Cat();
cat.eat() //吃东西
cat.fly() //我会飞
cat.sayName() //输出自己的名字
//判断数据类型
console.log(Object.prototype.toString.call(bool));//[object Boolean]
console.log(Object.prototype.toString.call(num));//[object Number]
console.log(Object.prototype.toString.call(str));//[object String]
console.log(Object.prototype.toString.call(und));//[object Undefined]
console.log(Object.prototype.toString.call(nul));//[object Null]
console.log(Object.prototype.toString.call(arr));//[object Array]
console.log(Object.prototype.toString.call(obj));//[object Object]
console.log(Object.prototype.toString.call(fun));//[object Function]
var objArr = {
0:12,
1:15,
2:23,
3:99,
length:4
}
const newArr = Array.prototype.slice.call(objArr );
/*
this指向objArr,
由于我们调用slice方法时并没有传入参数,所以start = 1,end = 4
就将伪数组转为真数组了
*/
//通过Array.prototype.slice.call()来转换伪数组是有条件限制的
//(1)对象里的属性名必须是连续的数字,并且属性名如果不是从0开始,需要给slice传参
//(2)伪数组里length属性的值必须是该对象中数字属性名的个数
通过Array.prototype.slice.call()来转换伪数组是有条件限制的