javaScript封装forEach,冒泡排序
Function.prototype.method=function(role,fn){
this.prototype[role]=fn;
return this;
}
if(!Array.prototype.forEach){
Array.method('forEach',function (fn,obj) {
/**
* fn是回掉函数
* obj是传来的对象,若无就只windows
* 可以直接用别的名字顶替,'forEachExp'
*/
const scope=obj||window;
console.log(scope,this)
for(var i=0;i<this.length;i++){
fn.call(scope,this[i],i,this)
}
})
}
// call(this指向,参数1,参数2,参数3)
// apply(this指向,[参数1,参数2....])
const arr=[9,15,20,6,47,5,75,36,3,68,42,14,53];
const arrs=['a','b','d','e','f'];
/**
* scope --> window
* method里面@this --> arr
*/
// arr.forEach(item=>{
// console.log(item,this)
// })
/**
* scope --> arrs
* method里面@this --> arr
* 但是当前函数的this指的是 window
* 因为箭头函数指定了@this 指向
*/
arr.forEach(item=>{
console.log(item,this)
},arrs)
/**
* scope --> @arrs
* method里面@this --> @arr
* 而此时当前函数的@this--->@window
*/
arr.forEach(function(item) {
console.log(item,this)
},arrs)
最近在研究设计模式,学桥接模式的时候看到了此案例。不过当时对我来说麻烦的是我居然一直搞不清call,bind,aplly。
哈哈现在搞定了
Array.method('bubbling',function(fn) {
for(let i=0;i<this.length;i++){
let item;
for(let n=0;n<this.length;n++){
if(this[i]<this[n]){
item=this[i];
this[i]=this[n];
this[n]=item;
}
}
}
fn.call(window,this)
})
arr.bubbling(function(item){
console.log(item)
})
不过貌似sort也蛮好用

浙公网安备 33010602011771号