JavaScript设计模式

对象的创建

1. var newObject = {}; 

2. var newObject = Object.create(null); 

3. var newObject = new Object();

//将键值赋值给一个对象
1. newObject.somekey = "Hello world";

2. newObject["somekey"] = "Hello world";

3. obj.definePreperty
//例如:
var man = Object.create(null);

// Properties can also be writable, enumerable and configurable
var config = {
  writable: true,
  enumerable: true,
  configurable: true
};

// Short-hand to use Object.defineProperty to add new properties
// with additional configuration 
var defineProp = function ( obj, key, value ){
  config.value = value;
  Object.defineProperty(obj, key, config);
}

defineProp( man, 'car',  'Delorean' );
defineProp( man, 'dob', '1981' );
defineProp( man, 'beard', false );

// And as we'll see a little later, this can even be used for inheritance
// like this..

var driver = Object.create( man );
defineProp (driver, 'topSpeed', '100mph');
driver.topSpeed // 100mph
4. Object.defineProperties
//例如
Object.defineProperties(newObject,{
  "someKey":{
      value:"Hello world",
      writable:true
  },
  "anoterKey":{
      value:"Foo bar",
      writable:false
  }
})

参考:
https://gist.github.com/aimoriu/1885392 https://github.com/heibor/ThinkByNightfall/wiki/JavaScript%E8%AE%BE%E8%AE%A1%E6%A8%A1%E5%BC%8F

单体模式

Singleton(单例)模式被熟知的原因是因为它限制了类的实例化次数只能一次。

单体模式的思想在于保证一个特定类仅有一个实例。
也就是使用同一个类创建新对象时,得到的对象和第一次创建的一模一样
JavaScript中没有类,只有对象。

工厂模式

工厂模式的目是为了创建对象。它通常在类或者类的静态方法中实现,具有:

  • 当创建相似对象时执行重复操作。
  • 在编译时不知道具体类型(类)的情况下,为工厂客户提供一种创建对象的接口。

迭代器模式

装饰者模式

策略模式

外观模式

代理模式

中介者模式

观察者模式

Observar(观察者)是一种设计模式,其中,一个对象(称为subject)维持一系列依赖于它(观察者)的对象,将有关状态的任何变更自动通知给它们。

工厂模式
function createPerson(opts){
    var person = {
        name: opts.name||"zhangrui"
    };
    person.sayName =  function(){
        alert(this.name);
    }
    return person;
}
var p1 = createPerson({name:"zhangrui"});
var p2 = createPerson({name:"jirengu"});
p1.sayName();
p2.sayName();

你可能感兴趣的:(JavaScript设计模式)