# 构造器模式

在面向对象编程中,构造器是一个特殊函数:当新建对象的内存被分配后,用来初始化该对象。而在JavaScript中几乎所有的东西都是对象,所以我们会关注对象的构造器。
对象构造器是被用来创建特殊类型的对象的,首先它要准备使用的对象,其次在对象初次被创建时,通过接收参数,构造器要用来对成员的属性和方法进行赋值。

做插件、类库,基本逃离不了构造器模式。因为构造器里面有类(构造函数)和实例。实例和实例都是单独存在的,各个实例能拥有自己的私有属性或方法,又能共同调用所处构造函数原型上的公共属性和方法。

对象创建

下面是我们创建对象的三种基本方式,下面的每一种都会创建一个新的对象:

  1. var newObject = {};
  2. // or
  3. var newObject = Object.create( null );
  4. // or
  5. var newObject = new Object();

为对象写入键值对

  1. // ECMAScript 3 兼容形式
  2. // 1. “点号”法
  3. // 设置属性
  4. newObject.someKey = "Hello World";
  5. // 获取属性
  6. var key = newObject.someKey;
  7. // 2. “方括号”法
  8. // 设置属性
  9. newObject["someKey"] = "Hello World";
  10. // 获取属性
  11. var key = newObject["someKey"];
  12. // ECMAScript 5 仅兼容性形式
  13. // For more information see: http://kangax.github.com/es5-compat-table/
  14. // 3. Object.defineProperty方式
  15. // 设置属性
  16. Object.defineProperty( newObject, "someKey", {
  17. value: "for more control of the property's behavior",
  18. writable: true,
  19. enumerable: true,
  20. configurable: true
  21. });
  22. // 如果上面的方式你感到难以阅读,可以简短的写成下面这样:
  23. var defineProp = function ( obj, key, value ){
  24. config.value = value;
  25. Object.defineProperty( obj, key, config );
  26. };
  27. // 为了使用它,我们要创建一个“person”对象
  28. var person = Object.create( null );
  29. // 用属性构造对象
  30. defineProp( person, "car", "Delorean" );
  31. defineProp( person, "dateOfBirth", "1981" );
  32. defineProp( person, "hasBeard", false );
  33. // 4. Object.defineProperties方式
  34. // 设置属性
  35. Object.defineProperties( newObject, {
  36. "someKey": {
  37. value: "Hello World",
  38. writable: true
  39. },
  40. "anotherKey": {
  41. value: "Foo bar",
  42. writable: false
  43. }
  44. });
  45. // 3和4中的读取属性可用1和2中的任意一种

在这本书的后面一点,这些方法会被用于对象的继承,如下:

  1. // 使用:
  2. // 创建一个继承与Person的赛车司机
  3. var driver = Object.create( person );
  4. // 设置司机的属性
  5. defineProp(driver, "topSpeed", "100mph");
  6. // 获取继承的属性 (1981)
  7. console.log( driver.dateOfBirth );
  8. // 获取我们设置的属性 (100mph)
  9. console.log( driver.topSpeed );

基础构造器

ES6以前,Javascript不支持类的概念,但它有一种与对象一起工作的构造器函数。使用new关键字来调用该函数,我们可以告诉Javascript把这个函数当做一个构造器来用,它可以用自己所定义的成员来初始化一个对象。
在这个构造器内部,关键字this引用到刚被创建的对象。回到对象创建,一个基本的构造函数看起来像这样:

  1. function Car( model, year, miles ) {
  2. this.model = model;
  3. this.year = year;
  4. this.miles = miles;
  5. this.toString = function () {
  6. return this.model + " has done " + this.miles + " miles";
  7. };
  8. }
  9. // 使用:
  10. // 我们可以示例化一个Car
  11. var civic = new Car( "Honda Civic", 2009, 20000 );
  12. var mondeo = new Car( "Ford Mondeo", 2010, 5000 );
  13. // 打开浏览器控制台查看这些对象toString()方法的输出值
  14. // output of the toString() method being called on
  15. // these objects
  16. console.log( civic.toString() );
  17. console.log( mondeo.toString() );

上面这是个简单版本的构造器模式,但它还是有些问题。一个是难以继承,另一个是每个Car构造函数创建的对象中,自己定义的toString()之类的函数都被重新定义。这不是非常好,重复地被定义会占用内存,理想的情况是所有Car类型的对象都应该引用同一个函数。 这要谢谢 ECMAScript3和ECMAScript5-兼容版,对于构造对象他们提供了另外一些选择,解决限制小菜一碟。

使用“原型”的构造器

为解决上述基础构造器的问题,

  1. function Car( model, year, miles ) {
  2. this.model = model;
  3. this.year = year;
  4. this.miles = miles;
  5. }
  6. // 注意这里我们使用Note here that we are using Object.prototype.newMethod 而不是
  7. // Object.prototype ,以避免我们重新定义原型对象
  8. Car.prototype.toString = function () {
  9. return this.model + " has done " + this.miles + " miles";
  10. };
  11. // 使用:
  12. var civic = new Car( "Honda Civic", 2009, 20000 );
  13. var mondeo = new Car( "Ford Mondeo", 2010, 5000 );
  14. console.log( civic.toString() );
  15. console.log( mondeo.toString() );

# 模块化模式

在JavaScript中,实现模块有几个选项,他们包括:

  • 模块化模式
  • 对象表示法
  • AMD模块
  • CommonJS 模块
  • ECMAScript Harmony 模块

# 单例模式

单例模式也称为单体模式。规定一个类只有一个实例,并且提供可全局访问点。

补充知识

构造函数中,如果return一个对象,那么在new该构造函数所得到的对象就是永恒这个对象,而不管你构造函数。

为什么需要单例模式

因为有的类比较庞大和复杂,其实例对象的创建和销毁对资源消耗就比较大。如果频繁地创建和销毁这些对象,并且这些对象完全是可以复用的话,那么将会造成不必要的性能浪费。
复用是指:我要一直使用new这个类后的实例对象的数据

下面根据代码理解何为具体复用:

  1. // 利用构造函数模拟账户余额
  2. function Account() {
  3. this.balance = 100
  4. }
  5. // 查询账户余额
  6. let check = new Account()
  7. console.log(check);/* Account { balance: 100 } */
  8. // 修改账户余额
  9. check.balance = 80
  10. // 查询账户余额
  11. let check2 = new Account()
  12. console.log(check2);/* Account { balance: 100 } */
  13. /* ---------------------进行修正,使得能正确更新账户余额----------------------- */
  14. // 模拟账户余额
  15. let ins = {
  16. balance: 100
  17. }
  18. function Account() {
  19. return ins
  20. }
  21. // 查询账户余额
  22. let check = new Account()
  23. console.log(check);/* { balance: 100 } */
  24. // 修改账户余额
  25. check.balance = 80
  26. // 查询账户余额
  27. let check2 = new Account()
  28. console.log(check2);/* { balance: 80 } */

↑这样修正后,有问题:就是数据不连贯;而且在ins对象在全局,很容易修改或者被覆盖。

  1. function Account() {
  2. this.balance = 100
  3. if(Account.instance) {
  4. // 如果函数对象的instance属性已经被赋值了,就返回这个属性
  5. return Account.instance
  6. }
  7. // 如果函数对象的instance属性未被赋值(即第一次new时),则为该属性赋值
  8. Account.instance = this
  9. /* 因为Account构造函数返回undefined,所以Account构造函数返回的是this指向的对象 */
  10. }
  11. // 查询账户余额
  12. let check = new Account()
  13. console.log(check);/* Account { balance: 100 } */
  14. // 修改账户余额
  15. check.balance = 80
  16. // 查询账户余额
  17. let check2 = new Account()
  18. console.log(check2);/* Account { balance: 80 } */

# 发布订阅模式