无法使用init和children定义对象

时间:2014-02-02 13:13:38

标签: javascript coffeescript

我正在定义以下对象,我打算在Mocha测试中使用它来模拟Mongoose模型。我是用Coffeescript写的,因此我无法访问function关键字:

TodoError = (body) ->
  @find = (query, callback) ->
    callback 'error', false
  @save = (query, callback) ->
    callback 'error', false
  @init = (body) -> {}
  @init body
  return @

通过以下方式调用此对象:

TodoError.find {}, (error, todos) -> {}

todo = new TodoError body
todo.save (error, todo) -> {}

当我尝试拨打TodoError.find

时,会出现以下错误
TypeError: Object function (body) {
  this.find = function(query, callback) {
    return callback('error', false);
  };
  this.save = function(query, callback) {
    return callback('error', false);
  };
  this.init = function(body) {
    return {};
  };
  this.init(body);
  return this;
} has no method 'find'

我最初使用以下定义为TodoError.find工作,但我意识到当我来到new TodoError部分时这不起作用:

  TodoError =
    find : (query, callback) ->
      callback 'error', false
    save : (query, callback) ->
      callback 'error', false

1 个答案:

答案 0 :(得分:0)

好的,我完全忘记了prototype的所有内容,然后终于找到了通往Coffeescript课程的方法,这个解决方案

class TodoError
  # constructor doesn't need to do anything.
  constructor: (body) ->

  #static methods.
  @find: (query, callback) ->
    callback 'error', false
  @findOne: (query, callback) ->
    callback 'error', false

  #instance methods.
  save: (callback) ->
    callback 'error', false

这编译为:

TodoError = (function() {
  function TodoError(body) {}

  TodoError.find = function(query, callback) {
    return callback('error', false);
  };

  TodoError.findOne = function(query, callback) {
    return callback('error', false);
  };

  TodoError.prototype.save = function(callback) {
    return callback('error', false);
  };

  return TodoError;

})();