CALL&APPLY(JS)
call 与 apply
功能:改变this的指向
区别:函数的参数风格不一样。
call实现:
js构造函数继承
js数据类型
console.log(Object.prototype.toString.call({})==='[object 0bject]');
//true
console.log(0bject.prototype.toString.call([]));
//[object Array]
es5 伪数组转换为真数组


改变this指向


手写call
查看代码
var name ='hhh'
var person = {
getName: function(){
return this.name
// 这个this怎么指向person1
}
}
var person1 = {name: 'sss'}
//参数接受的改变this指向的参数
Function.prototype.myCall = function (context){
//这里面的this是谁??
//这里的this必须要是一个function,否则error
if (typeof this !== 'function') {
throw new Error( 'error ')
}
context = context || window
//考虑参数
//拿到除了第一个参数之外的参数
var args = [...arguments].slice(1)
console.log(args);
//return 1234
console.log(this);
//要在person1上面来假设有一个方法,此处命名fn
context.fn = this
var result = context.fn(...args)
delete context.fn
return result
}
console.log(person.getName.myCall(person1,1,2,3,4));
![]()
手写apply
查看代码
//apply手写
var name ='hhh'
var person = {
getName: function(){
return this.name
}
}
var person1 = {name: 'sss'}
//参数接受的改变this指向的参数
Function.prototype.myApply = function (context){
if (typeof this !== 'function') {
throw new Error( 'error ')
}
context = context || window
context.fn = this
let result
if(arguments[1]){
result = context.fn(arguments[1])
}
else{
result = context.fn()
}
delete context.fn
return result
}
console.log(person.getName.myApply(person1,1,2,3,4));


浙公网安备 33010602011771号