第22章 高级技巧


# 第22章 高级技巧

# 高级函数

fucntion isArray(value) {
  return Obejct.prototpye.toString.call(value) == '[Obejct Array]'
}

function isFunction(value){ 
 return Object.prototype.toString.call(value) == "[object Function]"; 
} 
function isRegExp(value){ 
 return Object.prototype.toString.call(value) == "[object RegExp]"; 
}

# 作用域安全的构造函数

function Person(name, age, job) {
  if(this instanceof Person) {
    this.name = name;
  this.age = age;
  this.job = job;
  } else {
    return new Person(name, age, job)
  }

}

# 懒加载函数

# 函数柯里化

function curry(fn) {
  // args 获取第一个方法内的全部参数
  var args = Array.prototpye.slice.call(arguments,1);
  return function() {
    // 将后面方法里的全部参数和args进行合并
    var innerArgs = Array.prototype.slice.call(arguments);
    // 把合并后参数通过apply作为fn的参数并执行
    var finalArgs = args.concat(innerArgs);
    return fn.apply(null, finalArgs)
  }
}

function bind(fn, context) {
  var args = Array.prototype.slice(arguments,2);
  return function() {
    var innerArgs = Array.prototype.slice.call(arguments);
    var finalArgs = args.concat(innerArgs);
    return fn.apply(context, finalArgs)
  }

}

# 高级定时器

# 函数节流

function throttle(method, context) {
  clearTimeout(method.tId);
  method.tId = setTimeout(function() {
    method.call(context);
  }, 100)
}

# 自定义事件

function EventTarget() {
  this.handlers = {}
}
EventTarget.prototype = {
  constructor: EventTarget,
  addHandler: function(type, handler) {
    if (typeof this.handlers[type] == 'undefined')
  },
  fire: function() {},
  removeHandler: function() {}
}

上次更新: 1/3/2020, 9:54:38 PM