apply接受两个参数,第一个参数是this的指向,第二个参数是数组,当第一个参数为null、undefined的时候,默认指向window(因为apply第二个参数必须为数组,不是数组会报错,一些文章在写这个方法的时候没有进行判断)
测试数据
var person = function (city, country) {
return '姓 ' + this.firstName + " 名 " + this.lastName + " 出生在 " + city + country
}
var student = {
firstName: "张",
lastName: "三"
}
Function.prototype.newApply = function (student) {
if (student === null || student === undefined) return student = window
const sole = Symbol()
student.sole = this
let result
if ((arguments[1]) == undefined) result = student.sole()
if (!(arguments[1] instanceof Array)) return new Error('fail')
result = student.sole(...arguments[1])
delete student.sole
return result
}
const res = person.newApply(student, ["中国", "北京"]);
console.log(res)
call方法的第一个参数也是this的指向,后面传入的是一个参数列表,当第一个参数为null或undefined的时候,表示指向window
var person = function (city, country) {
return '姓 ' + this.firstName + " 名 " + this.lastName + " 出生在 " + city + country
}
var student = {
firstName: "张",
lastName: "三"
}
Function.prototype.newCall = function (student) {
if (student === null || student === undefined) return student = window
const sole = Symbol()
student.sole = this
const arg = [...arguments].slice(1)
const result = student.sole(...arg)
delete student.sole
return result
}
const res = person.newCall(student, "中国", "北京");
console.log(res)