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 :)
精彩评论