简体   繁体   English

从coffeescript中的类的属性中的方法访问属性的属性

[英]accessing properties of a property from a method in a property of a class in coffeescript

I want to be able to access a property of a class property from a method of a class property. 我希望能够从class属性的方法访问class属性的属性。

// 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 我该怎么做,如果我尝试foo.vars.bar ,它将返回undefined

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. 工作正常。

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原型(如您foo.vars访问foo.vars ,如下所示:

foo::vars.bar

( foo:: is a shortcut for foo.prototype in coffeescript) foo::foo.prototype中foo.prototype的快捷方式)

Or you could ensure that the context of bar is bound to an instance of foo when it's called. 或者,您可以确保bar的上下文在被调用时绑定到foo的实例。 One way to do this would be to bind it in the foo constructor: 一种方法是将其绑定到foo构造函数中:

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. 其中最合适的取决于您是否要在所有类中使用相同的vars对象。 The second option probably isn't suitable if you want the context of baz to be something other than a foo instance. 如果您希望baz的上下文不是foo实例,则第二个选项可能不合适。

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/ 小提琴: 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 @ ). 该解决方案将允许FOO的这种情况下, this_foo (重命名为您喜欢)其他不OPS结合它们或改变其价值被访问,以及this (或咖啡脚本@ )。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM