Function.property.call
函数功能:
- 改变this指向
- 接受不定向传参
思路:
1.如何改变this的指向
: 在指定作用域添加函数作为其属性: 使this优先指向该作用域
2.如何接受不定向传参
:es 6扩展远算符 + arguments类数组
let id = 10017;
let obj = {
id: 10018;
}
function Id(psw) {
console.log(this.id)
console.log(psw)
}
Id.call(obj)// 10018
Function.property.Mycall=function(context){
context.func = this;
context.func()
delete context.func()
}
Function.property.Mycall=function(context){
let context = context || window;
context.func = this;
let args = [];
for(let i=1,len=arguments.length,i<len,i++) {
args.push(arguments[i]);
}
let result = context.func(...args);
delete context.func();
return result;
}
Function.prototype.Mycall = function(content = window) {
content.func = this;
let args = [...arguments].slice(1);
let result = content.func(...args);
delete content.func;
return result;
}
apply
Function.prototype.apply2 = function(context = window) {
context.fn = this
let result;
// 判断是否有第二个参数
if(arguments[1]) {
result = context.fn(...arguments[1])
} else {
result = context.fn()
}
delete context.fn
return result
}