在coffeescript中分配类构造函数参数私有变量

时间:2014-08-22 15:34:55

标签: constructor coffeescript private

我发现我可以在coffeescript类中使用私有变量,如:

class Book
    title = null
    numberOfPages = null

    constructor: (t, nop) ->
        title = t
        numberOfPages = nop

    ripOutPages: (numPages) -> numberOfPages = numberOfPages - numPages

    isEmpty: -> numberOfPages == 0

所以我的第一个问题是,这被认为是coffeescript的合理方法吗?

我的第二个问题是,有没有更简洁的方法来实现这一点(即不必初始化类体中的变量然后在构造函数中分配它们)?

谢谢, 汤姆

2 个答案:

答案 0 :(得分:1)

如果查看生成的JS代码,您会发现它们更像是“私有”静态类属性,而不是“私有”实例属性:

var Book;

Book = (function() {
  var numberOfPages, title;

  title = null;

  numberOfPages = null;

  function Book(t, nop) {
    title = t;
    numberOfPages = nop;
  }

  Book.prototype.ripOutPages = function(numPages) {
    return numberOfPages = numberOfPages - numPages;
  };

  Book.prototype.isEmpty = function() {
    return numberOfPages === 0;
  };

  return Book;

})();

您创建的每个实例都共享相同的titlenumberOfPages个变量。所以我猜答案是:不,这不适合你想要做的事情。

JavaScript根本就没有“私有”属性。

答案 1 :(得分:0)

如果你真的非常想要"私人"变量,您可能希望将方法定义为闭包:

class Book
    constructor: (t, nop) ->
        # Those are two local variables:
        title = t
        numberOfPages = nop

        # The following closures will have access to the two variable above:
        @title = -> title                     # <- accessor to title
        @numberOfPages = -> numberOfPages     # <- accessor to numberoOfPage
        @ripOutPages = (numPages) -> numberOfPages = numberOfPages - numPages

    isEmpty: -> @numberOfPages() == 0
    # ^^^^^^^^^^^^^^^^
    # declared "as usual" as it uses accessor to access the "private" variables


# Some tests
lotr = new Book("The Lord of the Rings",1137)
hobbit = new Book("The Hobbit",276)

console.log lotr.title(), lotr.numberOfPages()
console.log hobbit.title(), hobbit.numberOfPages()

lotr.ripOutPages 100
console.log lotr.title(), lotr.numberOfPages()

产:

The Lord of the Rings 1137
The Hobbit 276
The Lord of the Rings 1037