0%

JavaScript设计模式——原型模式

原型模式的定义

用原型实例指向创建对象的类,使用于创建新的对象的类共享原型对象的属性以及方法。

使用场景:

创建新的对象的类共享原型对象的属性以及方法,多以继承来呈现。

我们可以通过 JavaScript 特有的原型继承特性去实现原型模式,也就是创建一个对象作为另一个对象的 prototype 属性值,可以通过 Object.create(prototype, optionalDescriptorObjects)来实现原型继承。

1
var someAnimal = {
2
  name: "喵星人",
3
  eat: function() {}
4
};
5
6
// 使用Object.create创建一个新的动物
7
var anotherAnimal = Object.create(someAnimal, {
8
  eat: {
9
    value: function() {
10
      console.log("吃骨头");
11
    }
12
  }
13
});
14
anotherAnimal.name = "汪星人";

如果我们不想通过Object.create去创建,则可以使用以下代码实现

1
var someAnimal = {
2
  name: "喵星人",
3
  init: function(name) {
4
    this.name = name;
5
  },
6
  eat: function(thing) {
7
    console.log("吃" + thing);
8
  }
9
};
10
11
function anotherAnimal(name) {
12
  function F() {}
13
  F.prototype = someAnimal;
14
  var f = new F();
15
  f.init(name);
16
  return f;
17
}
18
19
var anotherAnimalObj = anotherAnimal("狗");
20
anotherAnimalObj.eat("骨头");

在 ES6 里面,就简单了。。。

1
class Animal {
2
  constructor(name) {
3
    this.name = name;
4
  }
5
6
  eat(thing) {
7
    console.log("吃" + thing);
8
  }
9
}
10
11
class AnotherAnimal extends Animal {
12
  constructor(name) {
13
    super(name);
14
  }
15
}

得益于 ES6 的便利,这个模式不用再像之前一样,复杂的编码了,当然这个也只能在开发的时候使用,我们的 Babel 还是会把代码编译成为 ES5 的运行模式,方便代码浏览器和终端都能识别运行。