JavaScript 原型模式

161 阅读1分钟

用原型实例指定创建对象的种类,并且通过拷贝这些原型创建新的对象。

这种模式是实现了一个原型接口,该接口用于创建当前对象的克隆。当直接创建对象的代价比较大时,则采用这种模式。
JavaScript这种模式其实使用的比较少,但不是没有,prototype就是这种模式的实现。
在没es6的class时候实现继承则就用了此种模式

function Food (name) {
    this.name = name
}

Food.prototype.getName = function() {
    return this.name
}

function Cake(name) {
    Food.call(this, name)
}

// 通过 Object.create 创建(克隆)一个新的 Food.prototype 对象
Cake.prototype = Object.create(Food.prototype)
Cake.prototype.constructor = Cake

const cake = new Cake('cake')
console.log(cake.name)
console.log(cake.getName())
console.log(cake.__proto__.constructor)
console.log(cake.__proto__.constructor.prototype)