可回味的js代码段

1,关于bind()-----

1     var name="global";
2    var person={
3        name:"person",
4        hello:function(sth){
5                console.log(this.name+"say:"+sth);
6        }
7    };
8    console.log(person.hello.bind(person)("jj"));

模拟bind()-----

Function.prototype.bind = function(){  
  var fn = this, args = Array.prototype.slice.call(arguments), object = args.shift();  
  return function(){  
    return fn.apply(object,  
      args.concat(Array.prototype.slice.call(arguments)));  
  };  
};

2,模拟new function

 1     function foo(age) {
 2         this.age = age;
 3     }
 4 
 5     foo.construct = function() {
 6         var o = {}, Constructor = foo;
 7         o.__proto__ = Constructor.prototype;
 8         // FF 支持用户引用内部属性 [[Prototype]]
 9 
10         Constructor.apply(o, arguments);
11         return o;
12     };
13 
14     var obj1 = new foo(10);
15     var obj2 = foo.construct(10);
16     alert(obj2 instanceof foo);
17     // true
18     

3,数组去重

 1     Array.prototype.unique=function(){
 2         var newArr=[];
 3         var isExiteObj={};
 4         for(var i= 0,len=this.length;i<len;i++){
 5             if(!isExiteObj[this[i]]){
 6                 newArr.push(this[i]);
 7                 isExiteObj[this[i]]=1;
 8             }
 9         }
10         return newArr;
11     };
12     var arr=[8,5,6,8,5,9];
13     console.log(arr.unique());

4,删除数组----

1 Array.prototype.remove = function(from, to) {
2 var rest = this.slice((to || from) + 1 || this.length);
3 this.length = from < 0 ? this.length + from : from;
4 return this.push.apply(this, rest);
5 };

 5,求数组中的最大值,

var arr=[15,68,12,45,79];
var max=Math.max.apply(Math,arr);

6,判断对象时函数还是数组

function isArray(arr){
    var op=Object.prototype;
    if(op.toString.call(arr) == "[object Array]"){
        return true;
    }else{
        return false;
    }

}

function isFunction(fn){
    var op=Object.prototype;
    if(op.toString.call(fn) == "[object Function]"){
        return true;
    }else{
        return false;
    }

}

 

posted @ 2016-04-12 16:51  lokou  阅读(194)  评论(0编辑  收藏  举报