1.apply和call直接返回值,apply传参为数组,call传参为依次传
const obj = {
name:'obj',
}
function fn(a,b,c){
console.log(this, a,b,c)
}
fn.apply(obj,[1,2,3])
fn.call(obj,1,2,3)
2. bind返回一个绑定了传入对象的函数
const fn1 = fn.bind(obj,1,2,3)
fn1()
3.手写bind
Function.prototype.newBind = function(context, ...args){
if(typeof this !== 'function') throw new TypeError('error')
context = context|window
const _this = this
function BindOf(){
return _this.newApply(this instanceof BindOf? this : context, args)
}
BindOf.__proto__ = this.prototype
return BindOf
}
Function.prototype.newApply = function(context, args){
if(typeof this !== 'function') throw new TypeError('error')
context = context || window
context.fn = this
const result = args? context.fn(...args): context.fn()
delete context.fn
return result
}
fn.newBind(obj,1,2,3)()
4.new的过程以及手写new
function MyNew(fn, ...arr){
const obj = {}
obj.__proto__ = fn.prototype
fn.apply(obj, arr)
return obj
}
function Person(name, age){
this.name = name;
this.age = age;
this.sex = 'man'
}