【问题标题】:JavaScript prototype is not copied [closed]未复制 JavaScript 原型 [关闭]
【发布时间】:2012-08-21 04:08:35
【问题描述】:

出于某种原因,我用 CoffeeScript 编写的类没有复制原型。

这是我正在使用的确切代码:

module.exports = class ListQueue
  constructor: ->
    @queue = []
    @queueIds =[]
    @currentId = 0

  # Adds the given element to the queue.
  # Returns the index of the element.
  add: (el) ->
    @queueIds.push @currentId
    @queue.push el
    @currentId++ # return @lastIndex, then increment

  shift: ->
    @queueIndexes.shift()
    @queue.shift()

  # Returns the index in the @queue array for the given id.
  queueIndex: (id) ->
    for queueIndex, i in queueIndexes
      if queueIndex is id
        return i
    undefined

  get: (id) ->
    index = @queueIndex id
    @queue[index]

  length: ->
    @queue.length

  remove: (id) ->
    index = @queueIndex id
    if index?
      @queueIds = @queueIds.slice index, index
      @queue = @queue.slice index, index
      true
    else
      false

这是类的原型,正如预期的那样:

  { add: [Function],
  shift: [Function],
  queueIndex: [Function],
  get: [Function],
  length: [Function],
  remove: [Function] }

但这很奇怪:new ListQueue 实际上给了我这个:

  { queue: [], queueIds: [], currentId: 0 }

我正在使用 Node.JS 0.8.7。

【问题讨论】:

  • 如果您发布一些 JavaScript,也许有人可以帮助您。
  • 我不知道coffeescript,但是你能提供编译好的JavaScript吗?
  • 您的代码应该可以工作。你能发布一些代码来证明new Test() 上没有.do 吗?
  • 抱歉这个简短的问题,我用一些实际代码扩展了它。

标签: javascript node.js coffeescript


【解决方案1】:

do 函数实际上是存在的,如果你执行的话

new Test().do()

你会得到“测试”

如果您想要智能感知类型支持,请先尝试添加构造函数。它将创建函数变量并绑定它们,如下所示:

this.LoadData = __bind(this.LoadData, this);

这将允许您显式调用它们。

【讨论】:

  • 问题是do实际上并不存在。
  • 定义不存在?我运行了咖啡代码,并能够让它调用 do 函数。
  • 生成的对象完全是空的,这意味着该方法也不存在。奇怪的是它在浏览器(!)中运行良好,但在 Node 上对我来说不是本地的。
猜你喜欢
  • 1970-01-01
  • 2011-05-08
  • 1970-01-01
  • 2016-05-13
  • 2012-09-28
  • 2011-03-25
  • 1970-01-01
  • 2012-08-04
  • 2020-01-15
相关资源
最近更新 更多