简体   繁体   English

CoffeeScript类导致空对象

[英]CoffeeScript class results in empty object

I have a file 'a.coffee', with the following code: 我有一个文件“ a.coffee”,具有以下代码:

class Options
  options:
    # ...

  setOption: (name, value) ->
    # ...

  getOption: (name) ->
    # ...

# Export the Options class.
module.exports = Options

And file 'b.coffee': 和文件“ b.coffee”:

Options = require './a'
console.log new Options()

Of course, it is expected that when I run b.coffee, I will see this output: 当然,可以预期的是,当我运行b.coffee时,将看到以下输出:

{
  options: ...,
  setOption: function (name, value),
  getOption: function (name)
}

But instead, I get {} . 但是,我得到{}

How can I fix this? 我怎样才能解决这个问题?

Your expectations are wrong. 您的期望是错误的。 Everything at the class level goes in the object's prototype so given this: 类级别的所有内容都放在对象的原型中,因此有以下要求:

class C
  p: 6
  m: ->
o = new C

the object o will be empty because there are no instance variables but if you look at the "class" (via Object.prototype.constructor to get the "class" and :: to get the prototype): 对象o将为空,因为没有实例变量,但是如果您查看“类”(通过Object.prototype.constructor来获取“类”,并通过::来获取原型):

o.constructor::p

you'll see things. 你会看到的。

If you add some instance variables (ie something that really is part of your object): 如果添加一些实例变量(即实际上属于对象的一部分):

class C
  constructor: -> @p = 6

then you'll see them in the object: 然后您将在对象中看到它们:

c = new C
console.log c
# { p: 6 } will appear in the console

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM