首页 > 代码库 > javascript设计模式1

javascript设计模式1

带原型的Constructor模式

function Car(model, year, miles){

  this.model = model;

  this.year = year;

  this.miles = miles;

}

Car.prototype.toString = function(){

  return this.model + " has done " + this.miles + " miles";

};

var civic = new Car("Honda Civic", 2009, 2000);

alert(civic.toString()); 

 

Module 模式

1. 对象字面量表示法 2. Module模式 3. AMD 模块 4. CommonJS模块 5. ECMAScript Harmony 模块

# 对象字面量表示法

var myModule = {

  myProperty: "someValue",

  myConfig: {

    language: "en"

  },

  myMethod: function(){

    alert(‘xxx‘);

  },

  myMethod2: null

}

# Module 模式

var testModule = (function(){
  var counter = 0;

  return {

    increment: function(){

      return ++counter;

    },

    reset: function(){

      counter = 0;

    }

  };

})();

javascript设计模式1