将JS设计模式转换为CoffeeScript发生了类错误

时间:2014-01-29 23:30:41

标签: javascript coffeescript

在俄罗斯维基百科上,我找到了Builder设计模式的代码,并尝试将其转换为coffeescript。 Builder.js

这是Builder.coffee

的要点
// Abstract Builder
function PizzaBuilder() {
    var pizza = new Pizza();
    this.getPizza = function() {
        return pizza;
    };
    this.createNewPizzaProduct = function() {
        pizza.clear();
    };
    this.buildDough = function(val) { };
    this.buildSauce = function(val) { };
    this.buildTopping = function(val) { };
}
// ConcreteBuilder
function HawaiianPizzaBuilder() {
    PizzaBuilder.call(this);
    var pizza = this.getPizza(); // imitation protected
    this.buildDough = function() { pizza.setDough("cross"); };
    this.buildSauce = function() { pizza.setSauce("mild"); };
    this.buildTopping = function() { pizza.setTopping("ham+pineapple"); };
}

我将构造函数调用的每个函数(新的FuncName)都更改为class FuncName,但构造函数中的PizzaBuilder.call(this);发生了错误。

PizzaBuilder = ->
    pizza = new Pizza()
    @getPizza = -> pizza
    @createNewPizzaProduct = -> pizza.clear()
    @buildDough = (val) ->
    @buildSauce = (val) ->
    @buildTopping = (val) ->

class HawaiianPizzaBuilder
    PizzaBuilder.call this
    pizza = @getPizza() # imitation protected
    buildDough: -> pizza.setDough "cross"
    buildSauce: -> pizza.setSauce "mild"
    buildTopping: -> pizza.setTopping "ham+pineapple"

1 个答案:

答案 0 :(得分:2)

在javascript函数中HawaiianPizzaBuilder是类的构造函数。在Coffeescript中,您需要将其明确定义为constructor方法,这样:

class HawaiianPizzaBuilder
    constructor: ->
       PizzaBuilder.call this
       pizza = @getPizza() # imitation protected
       @buildDough: -> pizza.setDough "cross"
       @buildSauce: -> pizza.setSauce "mild"
       @buildTopping: -> pizza.setTopping "ham+pineapple"

您在this.函数定义之前忘记了build...

但是我想建议另一个版本相同的模式示例,因为coffeescript提供了更简单的类继承语法,类似于:

class PizzaBuilder
    constructor: ->
        @pizza = new Pizza()
    buildDough: -> @
    buildSauce: -> @
    buildTopping: -> @

class HawaiianPizzaBuilder
    buildDough: -> 
        @pizze.setDough "cross"
        @
    #...override other methods


 builder = new HawaiianPizzaBuilder
 myPizza = builder.buildDough().buildSauce().pizza