手写call,apply,bind
Function.prototype._call = function (ctx, ...args) {
const fn = Symbol('fn')
console.log('...', ...args)
console.log('args', args)
let context = ctx || window
context.fn = this
let result = args.length > 0 ? context.fn(...args) : context.fn()
delete context.fn
return result
}
Function.prototype._apply = function (ctx, args = []) {
const fn = Symbol('fn')
if (!(args && args instanceof Array)) {
throw ('请传入数组')
}
let context = ctx || window
context.fn = this
let result = args.length > 0 ? context.fn(...args) : context.fn()
delete context.fn
return result
}
Function.prototype._bind = function (ctx, ...args) {
let that = this
return function () {
return that._call(ctx, ...args)
}
}
var name = "1";
var obj = {
name: 2,
prop: {
name: 3,
getName: function (age, s) {
return {
name: this.name,
age: age,
s: s
}
}
}
}
console.info(obj.prop.getName(3, 4));
console.info(obj.prop.getName.call(obj, 3, 4));
console.info('_call实现', obj.prop.getName._call(this, 3, 4));
console.info('_apply实现', obj.prop.getName._apply(this, [2, 3]));
let bindHandle = obj.prop.getName._bind(this, 2, 3)
console.log('bindHandle()', bindHandle())
后续文章输出
- 在手写bind中,其实也有闭包的引用,下一文就讲讲闭包