call
call 方法在使用一个指定的 this 和若干个参数的情况下调用某个函数或方法。例如:
<script>
let foo = {
value: "foo"
};
function pri() {
console.log(this.value);
}
pri.call(foo); //foo
</script>
模拟实现要注意以下:
(1)call 改变了 pri 的 this 的指向,指向到 foo
(2)pri 函数执行了
(3)call 函数可以传递参数
(4)传入的 this 可以为 null,当 this 为 null 的时候,默认指向 window。
(5)函数是可以有返回值的
<script>
let foo = {
value: "foo"
};
function pri(name, age) {
console.log(this.value);
return {
value: this.value,
name: name,
age: age
}
}
Function.prototype.change = function(context) {
context = context == null? window : context;
//如果传入的 this 为 null,则指向 window
context.fn = this;
//获取调用这个函数的函数
let arr = [];
for (let i = 1; i < arguments.length; i++) {
arr.push(arguments[i]);
}
//获取参数
//第一个参数为传入的 this,所以从第二个开始获取
let result = context.fn(...arr);
//传入参数并执行该函数
//(...)可以将可迭代对象拆分,并将迭代返回的每个值单独传入
delete context.fn;
//delete 操作符用于删除对象的某个属性
return result;
//返回结果
}
</script>
效果:
apply
类似于 call,不过 apply 方法第二个参数为一个数组。
<script>
let foo = {
value: "foo"
};
function pri(name, age) {
console.log(this.value);
return {
value: this.value,
name: name,
age: age
}
}
Function.prototype.change = function(context, arr) {
context = context == null? window : context;
//如果传入的 this 为 null,则指向 window
context.fn = this;
//获取调用这个函数的函数
let result;
//返回值
if (arr == null) {
result = context.fn();
} else {
result = context.fn(...arr);
}
//传入参数并执行该函数
//(...)可以将可迭代对象拆分,并将迭代返回的每个值单独传入
delete context.fn;
//delete 操作符用于删除对象的某个属性
return result;
//返回结果
}
</script>
效果:
火锅真好吃!