いくつかのよくある手書きjsテーマ

7514 ワード

1、コール
Function.prototype.call2 = function(content = window) {
    content.fn = this;
    let args = [...arguments].slice(1);
    let result = content.fn(...args);
    delete content.fn;
    return result;
}
let foo = {
    value: 1
}
function bar(name, age) {
    console.log(name)
    console.log(age)
    console.log(this.value);
}
bar.call2(foo, 'black', '18') // black 18 
2、アプリ
Function.prototype.apply2 = function(context = window) {
    context.fn = this
    let result;
    //           
    if(arguments[1]) {
        result = context.fn(...arguments[1])
    } else {
        result = context.fn()
    }
    delete context.fn
    return result
}
3、ビン
Function.prototype.bind2 = function(content) {
    if(typeof this != "function") {
        throw Error("not a function")
    }
    //              
    let fn = this;
    let args = [...arguments].slice(1);
    
    let resFn = function() {
        return fn.apply(this instanceof resFn ? this : content,args.concat(...arguments) )
    }
    function tmp() {}
    tmp.prototype = this.prototype;
    resFn.prototype = new tmp();
    
    return resFn;
}
ビッド2
Function.prototype.bind2 = function (context) {
    var self = this;
    var args = Array.prototype.slice.call(arguments, 1);

    var fbound = function () {

        var bindArgs = Array.prototype.slice.call(arguments);
        //         ,this     ,self       ,       `fbound.prototype = this.prototype;`,      fbound.prototype         prototype,      true,     true    ,this     。
        //         ,this    window,self       ,      false,     false    ,this       context。
        self.apply(this instanceof self ? this : context, args.concat(bindArgs));
    }
    //         prototype        prototype,               
    fbound.prototype = this.prototype;
    return fbound;
}
4、ディープコピー
function deepCopy(obj){
    //           ,
    if(typeof obj == "object"){
        //      
        var result = Array.isArray(obj) ? [] : {};
        for(let i in obj){
            result[i] = typeof obj[i] == "object" ? deepCopy(obj[i]) : obj[i];
        }
    }else {
        //          ==   
        var result = obj;
    }
    return result;
}
5、new
        
          .
                 .          .
                 ,        ,   ,         

function _new(obj, ...rest){
  //   obj           
  const newObj = Object.create(obj.prototype);

  //          newObj ,    obj       .
  const result = obj.apply(newObj, rest);

  //                  ,        ,   ,         
  return typeof result === 'object' ? result : newObj;
}
6、ブレ防止
    function debounce(fn) {
      // 4、                 
      let timeout = null;
      return function() {
        // 5、       /     ,         
        clearTimeout(timeout);
        // 6、         setTimeout,
        //              interval    
        //           ,      fn   
        timeout = setTimeout(() => {
          fn.call(this, arguments);
        }, 1000);
      };
    }
7、スロットル
   function throttle(fn) {
      // 4、          
      let canRun = true;
      return function() {
        // 5、             true,   true      
        if(!canRun) {
          return;
        }
        // 6、  canRun     false,          
        canRun = false;
        // 7、   
        setTimeout( () => {
          fn.call(this, arguments);
          // 8、     (       )  ,           true
          canRun = true;
        }, 1000);
      };
    }
8、プロミス
var promise = new Promise((resolve,reject) => {
    if (    ) {
        resolve(value)
    } else {
        reject(error)
    }
})
promise.then(function (value) {
    // success
},function (value) {
    // failure
})
9、プロミス A+
function myPromise(constructor){
    let self=this;
    self.status="pending" //            
    self.value=undefined;//     resolved      
    self.reason=undefined;//     rejected      
    function resolve(value){
        //  ==="pending",             
       if(self.status==="pending"){
          self.value=value;
          self.status="resolved";
       }
    }
    function reject(reason){
        //  ==="pending",             
       if(self.status==="pending"){
          self.reason=reason;
          self.status="rejected";
       }
    }
    //      
    try{
       constructor(resolve,reject);
    }catch(e){
       reject(e);
    }
}
  ,   myPromise           then  :
myPromise.prototype.then=function(onFullfilled,onRejected){
   let self=this;
   switch(self.status){
      case "resolved":
        onFullfilled(self.value);
        break;
      case "rejected":
        onRejected(self.reason);
        break;
      default:       
   }
}
10、一つのイベントを実現する.
//     ,          
class EventEmitter {
  constructor () {
    //     
    this.events = this.events || new Map()
  }
  //     
  addListener (type, fn) {
    if (!this.events.get(type)) {
      this.events.set(type, fn)
    }
  }
  //     
  emit (type) {
    let handle = this.events.get(type)
    handle.apply(this, [...arguments].slice(1))
  }
}

//   
let emitter = new EventEmitter()
//     
emitter.addListener('ages', age => {
  console.log(age)
})
//     
emitter.emit('ages', 18)  // 18
11、双方向データバインディングを実現する
let obj = {}
let input = document.getElementById('input')
let span = document.getElementById('span')
//     
Object.defineProperty(obj, 'text', {
  configurable: true,
  enumerable: true,
  get() {
    console.log('     ')
  },
  set(newVal) {
    console.log('     ')
    input.value = newVal
    span.innerHTML = newVal
  }
})
//     
input.addEventListener('keyup', function(e) {
  obj.text = e.target.value
})
12、Object.creatの基本実現原理
//   :          
function create(obj) {
  function F() {}
  F.prototype = obj
  return new F()
}

12、urlパラメータを取得する
/**
 * [  URL            ]
 *   URL:http://htmlJsTest/getrequest.html?uid=admin&rid=1&fid=2&name=  
 * @param {[string]} urlStr [          ,    url      ]
 * @return {[string]}       [    ]
 */
function GetRequest(urlStr) {
    if (typeof urlStr == "undefined") {
        var url = decodeURI(location.search); //  url "?"      
    } else {
        var url = "?" + urlStr.split("?")[1];
    }
    var theRequest = new Object();
    if (url.indexOf("?") != -1) {
        var str = url.substr(1);
        strs = str.split("&");
        for (var i = 0; i < strs.length; i++) {
            theRequest[strs[i].split("=")[0]] = decodeURI(strs[i].split("=")[1]);
        }
    }
    return theRequest;
}
13、検索配列の最小値
function arrayMin(arrs){
    var min = arrs[0];
    for(var i = 1, ilen = arrs.length; i < ilen; i+=1) {
        if(arrs[i] < min) {
            min = arrs[i];
        }
    }
    return min;
}
//     
var rets = [2,4,5,6,7,9,10,15];
console.log(arrayMin(rets));//2
14、配列内で最大値を検索する
function arrayMax(arrs) {
    var max = arrs[0];
    for(var i = 1,ilen = arrs.length; i < ilen; i++) {
        if(arrs[i] > max) {
            max = arrs[i];
        }
    }
    return max;
}