javascript函数与对象

JavaScript

函数

存储函数

var store = {
  nextId: 1,
  cache: {},
  add: function(fn) {
    if (!fn.id) {
      fn.id = this.nextId++;
      this.cache[fn.id] = fn;
    }
  }
};

自记忆函数

function isPrime(value) {
  if (!isPrime.results) {
    isPrime.results = {};
  }
  if (isPrime.results[value] !== undefined) {
    return isPrime.results[value];
  }
  var prime = value !== 0 && value !== 1;
  for (var i = 2; i < value; i++) {
    if (value % i === 0) {
      prime = false;
      break;
    }
  }
  return (isPrime.results[value] = prime);
}

函数定义

  1. 函数定义和函数表达式
    function add(a,b){return a+b;}
  2. 箭头函数
    var add = (a, b) => a + b;
  3. 函数构造函数
    var add = new Function("a", "b", "return a + b");
  4. 生成器函数(ES6)
    function* myGen(){yeild 1};

函数内部声明变量的时候,一定要使用 var、const或let 声明。如果不用的话,你实际上声明了一个全局变量.

闭包

window.onload = function() {
  var aLi = document.getElementsByTagName("li");
  for (var i = 0; i < aLi.length; i++) {
    (function(i) {
      aLi[i].onclick = function() {
        alert(i);
      };
    })(i);
  }
};

对象

继承

原型继承

function extend(Child, Parent) {
  if (Child == null) throw TypeError("child is null");
  if (Parent == null) throw TypeError("parent is null");
  let childType = typeof Child;
  if (childType === "object" || childType !== "function")
    throw TypeError("child type is not construct function");
  let parentType = typeof Parent;
  if (parentType === "object" || parentType !== "function")
    throw TypeError("parent type is not construct function");

  const F = function() {};
  F.prototype = Parent.prototype;
  Child.prototype = new F();
  Child.prototype.constructor = Child;
  Child.uber = Parent.prototype;
}

function extend2(Child, Parent) {
  var p = Parent.prototype;
  var c = Child.prototype;
  for (var i in p) {
    c[i] = p[i];
  }
  c.uber = p;
}

function inherit(p) {
  if (p == null) throw TypeError("parent is null");
  if (Object.create) {
    return Object.create(p);
  }
  let t = typeof p;
  if (t !== "object" && t !== "function")
    throw TypeError("parent type is not object");

  function F() {}

  F.prototype = p;
  return new F();
}

你可能感兴趣的:(javascript函数与对象)