在 javascript 对象中存储函数引用

Store function reference in javascript object

我猜这应该很简单,但我被卡住了。如何将对方法的引用存储在另一个原型对象中(在本例中为 actions)?在下面的方式中,我的 someFn 和 anotherFn 方法未定义。

class MyClass

  constructor: ->
    console.log @actions # returns
    # returns:
    # Object {someFn: undefined, anotherFn: undefined, someText "I am some text"}

  actions:
     someFn: @someFn
     anotherFn: @anotherFn
     someText: 'I am some text'

  someFn: ->
    console.log 'I am some function'

  anotherFn: ->
    console.log 'I am another function'

我正在使用 CoffeeScript,但对于任何普通的 JSers 我们都有 -

  MyClass = function MyClass() {
    console.log(this.actions);
  }

  MyClass.prototype.actions = {
    someFn: MyClass.someFn,
    anotherFn: MyClass.anotherFn,
    someText: 'I am some text'
  };

  MyClass.prototype.someFn = function() {
    return console.log('I am some function');
  };

  MyClass.prototype.anotherFn = function() {
    return console.log('I am another function');
  };

原型上不能有这样的对象。您需要将其设为实例 属性:

class MyClass
  constructor: ->
    @actions =
      someFn: @someFn
      anotherFn: @anotherFn
      someText: 'I am some text'
    console.log @actions # works as expected

  someFn: ->
    console.log 'I am some function'

  anotherFn: ->
    console.log 'I am another function'

如果出于某种原因您确实需要一个带有原型函数的对象,请使用 :: 访问它们(在创建 action 对象的静态上下文中):

…
  someFn: …
  anotherFn: …
  actions:
     someFn: @::someFn
     anotherFn: @::anotherFn
     someText: 'I am some text'