
实现apply方法
js
Function.prototype.myApply = function (context, args = []) {
let ctx = context || window
// 将当前被调用的方法定义在ctx.func上,对象方法绑定this
// 新建一个唯一的值存
let func = Symbol()
ctx[func] = this
const res = args.length > 0 ? ctx[func](...args) : ctx[func]()
delete ctx[func]
return res
}js
Function.prototype.myApply = function (context = window, ...args) {
// this --> func context --> obj args --> 传递过来的参数
// 在context上加一个唯一值不影响context上的属性
let key = Symbol('key')
context[key] = this
let result = context[key](args)
delete context[key]
return result
}js
Function.prototype.myApply = function (context, args) {
if (!context || context === null) {
context = window
}
// 创建唯一的key
let fn = Symbol()
context[fn] = this
return context[fn](...args)
}js
Function.prototype.myApply = function (context, arr) {
var context = Object(context) || window
context.fn = this
var result
if (!arr) {
result = context.fn()
} else {
var args = []
for (var i = 0, len = arr.length; i < len; i++) {
args.push('arr[' + i + ']')
}
result = eval('context.fn(' + args + ')')
}
delete context.fn
return result
}
