封装数组去重的方法(对象去重)
Array.prototype.de-weight=function(){
let obj={}
this.foreach(item=>{
obj[item]=item
})
this.length=0;//去掉原有的项
for(k in obj){
this.push(obj[k])
}
封装call
Function.prototype.mycall=function(context,...arg){
context=context||window// 给context一个判断值,如果没有传参的话,让this指向window
let a=symbol()
context.a=this
let res= context.a(context,...arg)
delete context.a
return res
}
封装apply
Function.prototype.myapply=function(context,ary){//跟call的区别就是这个传入的是是一个整体的数组
ary=ary||[]
context=context||window
let a=symbol()
context.a=this;
let res=context(context,ary)
delete context.a
return res
}
封装bind
Function.prototype.mybind=function(context,...ary){
_this=this;
return function(...ary){
return _this.apply(context,arg.concat(arg)
}
}
封装new
function mynew(...arg){
let obj={}//创建一个空的新的堆内存
let construor=arg.shift()//提取出来第一项,运行
obj.__proto__=construor.prototype//把函数类的原型赋给新堆内存的原型链上
var res= construor.call(obj....arg)//用call执行改变函数执行的this指向
return typeof res='object' ? res : obj//判断返回的数据是什么类型,如果是引用数据类型则直接返回res,如果不是的话,就返回一个空对象出去