原型模式的实现关键,是语言本身是否提供了clone方法。ECMAScript 5提供了Object.create方法,可以用来克隆对象
var Plane = function(){
this.blood = 100;
this.attackLevel = 1;
this.defenseLevel = 1;
};
var plane = new Plane();
plane.blood = 500;
plane.attackLevel = 10;
plane.defenseLevel = 7;
var clonePlane = Object.create( plane );
console.log( clonePlane.blood ) //输出500
console.log( clonePlane.attackLevel ) //输出10
console.log( clonePlane.defenseLevel ) //输出7
在不支持Object.create方法的浏览器中,则可以使用以下代码
Object.create = Object.create || function( obj ){
var F = function(){};
F.prototype = obj;
return new F();
}
原型模式不仅仅是一种设计模式,也是一种编程范型。JavaScript就是使用原型模式来搭建整个面向对象系统的。在JavaScript语言中不存在类的概念,对象也并非从类中创建出来的,所有的JavaScript对象都是从某个对象上克隆而来的。
es6提供了Class语法,来实现继承,但其背后仍是通过原型机制来创建对象:
class Animal {
constructor(name) {
this.name = name;
}
getName() {
return this.name;
}
}
class Dog extends Animal {
constructor(name) {
super(name);
}
speak() {
return "woof";
}
}
var dog = new Dog("Scamp");
console.log(dog.getName() + ' says ' + dog.speak());