开发者

Correct way to refer to class/instance rather than object literal property?

I have an object 'foo', with an object literal as a property, as shown below. Inside that property, I'd like to refer to the object 'foo' rather than the object literal itself.

Can this only be done with hacks, ie, referring to the obje开发者_开发百科ct by its variable name? Or is there a better way?

Example below - should print 'woo' on success.

class Foo
  myfunc: =>
    console.log('woo')
  testthing: {
    'foo':'bar'
    'baz':'boo'
    'bop': =>
      @myfunc()
  }

window.foo = new Foo

foo.testthing.bop()


class Foo
  constructor: ->
    @testthing =
      'foo':'bar'
      'baz':'boo'
      'bop': => @myfunc()
  myfunc: =>
    console.log('woo')

Declaring testthing in the constructor like this allows @myfunc to be bound to the 'instance' rather than the 'class'.

You could also use 'bop': @myfunc instead of 'bop': => @myfunc() to pass along any arguments :)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜