本身總結的手寫代碼片斷

面試夠用面試

/** * 模仿 new * @return {[type]} [description] */
function createNew() {
  var obj = {};
  let context = [].shift.call(arguments); // 獲取構造函數
  obj.__proto__ = context.prototype;
  context.apply(obj, [...arguments]);
  return obj;
}

// @test
function Person(name) {
  this.name = name;
}
var p = createNew(Person, 'zjj');
console.log(p);
// @test


/** * 模仿實現 instanceof * @param {[type]} left [左側參數爲一個實例對象] * @param {[type]} right [右側爲要判斷的構造器函數] * @return {[type]} [true / false] */
function instanceOf (left, right) {
  let prototype = right.prototype; // 獲取目標原型對象

  left = left.__proto__;

  while (true) {
    if(left == null) {
      return false;
    } else if (left == prototype) {
      return true;
    }
    left = left.__proto__
  }
}

/** * 模仿call * @param {[type]} context [要綁定的this對象] * @return {[type]} [返回函數執行結果] */
Function.prototype.call_new = function(context) {
  var context = context || window;
  context.fn = this;

  var args = [...arguments].clice(1);
  let result = context.fn(...args);
  delete context.fn;
  return result;
}


// @test

// foo.call_new(obj, 1,2,3)


/** * 模仿apply * @param {[type]} context [要綁定的this對象] * @return {[type]} [執行結果] */
Function.prototype.apply_new = function(context) {
  var context = context || window;

  context.fn = this;

  var args = [...arguments][1];
  let result;
  if(args) {
    result = context.fn(...args);
  } else {
    result = context.fn()
  }

  delete context.fn;
  return result;

}


/** * 模仿 bind * @param {[type]} context [要綁定的this對象] * @return {[type]} [執行結果] */
Function.ptototype.bind_new(context) {
  var self = this;
  var args = [...arguments].slice(1);
  return function() {
    var args1 = [...arguments].slice(1);
    return self.apply(context, args.concat(args1));
  }
}


/** * 函數放抖 * @param {Function} fn [目標函數] * @param {[type]} delay [延遲] * @param {[type]} immit [是否第一次觸發的時候執行一次] * @return {[type]} [description] */
function debounce(fn, delay, immit) {
  var timer;
  var firstisOk;

  return function() {

    var self = this;
    var args = arguments;
    timer && clearTimeout(timer);


    if(immit && !firstisOk) {
      fn.apply(self, args);
      firstisOk = true;
    }
    timer = setTimeout(() => {
      fn.apply(self, args);
      firstisOk = false;
    }, delay);
  }
}

/** * 節流 * @param {Function} fn [目標函數] * @param {[type]} delay [延遲時間] * @return {[type]} [description] */
function throttle(fn, delay) {
  let timer,
      startTime;

  return function() {
    let self = this;
    let args = arguments;

    timer && clearTimeout(timer)

    if(!startTime) {
      startTime = Date.now();
    }

    if(Date.now() - startTime > delay) {
      fn.apply(self, args)
      startTime = Date.now();
    } else {
      timer = setTimeout(() => {
        fn.apply(self, args);
      }, delay)
    }
  }
}


/** * 深拷貝 * @param {[type]} p [目標對象] * @param {[type]} c [拷貝後的對象] * @return {[type]} [description] */
function extendsDeeply(p, c) {
  var c = c || {};

  for(var i in p) {
    if(typeof p[i] == 'object') {
      c[i] = (p[i] instanceof == Array) ? [] : {}
      extendsDeeply(p[i], c[i]);
    } else {
      c[i] = p[i]
    }
  }
}


// 手寫一個繼承
function Parent(name) {
  this.name = name;
}

Parent.prototype.getName = function() {
  console.log(this.name);
}

function Child(name, age) {
  Parent.call(this, name);
  this.age = age;
}

function create(prototype) {
  function F(){};
  F.prototype = prototype;
  return new F();
}
Child.prototype = create(Parent.ptototype);
Child.prototype.constructor = Child;
Child.prototype.getAge = function() {
  console.log(this.age)
}


// 簡單實現一個簡單的promise
function myPromise(constructor) {
  let self = this;
  self.status = "pending" //定義狀態改變前的初始狀態
  self.value = undefined; //定義狀態爲resolved的時候的狀態
  self.reason = undefined; //定義狀態爲rejected的時候的狀態

  function resolve(value) {
    if (self.status === "pending") {
      self.value = value;
      self.status = "resolved";
    }
  }

  function reject(reason) {
    if (self.status === "pending") {
      self.reason = reason;
      self.status = "rejected";
    }
  }

  //捕獲構造異常
  try {
    constructor(resolve, reject);
  } catch (e) {
    reject(e);
  }
}


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:
  }
}

var p =  new myPromise(function(resolve, reject) {
  resolve(1);
});

p.then((res) => {
  console.log(res);
})


// 數組去重


// 手寫ajax

var xhr = new XMLHttpRequest();
xhr.open('post', 'http://', true); // 初始化一個請求 xhr.open(method, url, async);
  if(xhr.readyState == 4) {
    if((xhr.status >= 200 && xhr.status < 300) || xhr.status == 304) {
      console.log(xhr.responseText);
    }
   }
}

let postData = {"name1":"value1","name2":"value2"};
postData = (function(value) {
  var dataString = "";
  for(var key in value){
       dataString += key+"="+value[key]+"&";
  };
  return dataString;
})(postData);

xhr.setRequestHeader("Content-type","application/x-www-form-urlencoded"); // 用於設置HTTP請求頭,此方法必須在open()方法和send()之間調用
// 異常處理
xhr.onerror = function() {
   console.log('Network request failed')
}
// 跨域攜帶cookie
xhr.withCredentials = true;
xhr.send(postData); // 用於發送HTTP請求,即調用該方法後HTTP請求才會被真正發出,send的參數能夠是string和blob

複製代碼
相關文章
相關標籤/搜索