Reputation: 3166
I want to be able to access a property of a class
property from a method of a class
property.
// lets say
class foo
constructor: () ->
vars: {
bar: "somevalue"
},
op: {
baz: () ->
#get the value of foo.vars.bar
}
How do I do it, it returns undefined if i try foo.vars.bar
EDIT
Sorry for not making it so clear, I want
baz: () ->
something = foo.vars.bar
Is there a simple way to do it, because
baz: () ->
something = foo.prototype.vars.bar
works fine.
Upvotes: 0
Views: 50
Reputation: 9559
I can think of two ways you can do this: always access foo.vars
via the foo prototype (as you've discovered) like this:
foo::vars.bar
(foo::
is a shortcut for foo.prototype
in coffeescript)
Or you could ensure that the context of bar
is bound to an instance of foo
when it's called. One way to do this would be to bind it in the foo
constructor:
class foo
constructor: () ->
@op.baz = @op.baz.bind @
vars: {
bar: "somevalue"
},
op: {
baz: () ->
console.log @vars.bar
}
Which of these is most suitable probably depends on whether you want to use the same vars
object across all classes or not. The second option probably isn't suitable if you want the context of baz
to be something other than a foo
instance.
Upvotes: 2
Reputation: 4471
One potential way is to have the parent instance variable defined in the scope:
class foo
this_foo = null # So that the var is available everywhere within this context block
constructor: () ->
this_foo = @
vars: {
bar: "somevalue"
},
op: {
baz: () ->
this_foo.vars.bar
}
console.log (new foo).op.baz() # => somevalue
Fiddle: http://jsfiddle.net/XL9aH/3/
This solution will allow this instance of foo, this_foo
(rename to your liking) to be accessed in other ops as well without binding them or changing their value for this
(or coffee-script @
).
Upvotes: 2