简体   繁体   English

引用类/实例而不是 object 文字属性的正确方法?

[英]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.我有一个 object 'foo',其中一个 object 文字作为属性,如下所示。 Inside that property, I'd like to refer to the object 'foo' rather than the object literal itself.在该属性中,我想引用 object 'foo' 而不是 object 文字本身。

Can this only be done with hacks, ie, referring to the object by its variable name?这只能通过黑客来完成,即通过变量名引用 object 吗? Or is there a better way?或者,还有更好的方法?

Example below - should print 'woo' on success.下面的示例 - 成功时应打印“woo”。

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'.像这样在构造函数中声明testthing允许@myfunc绑定到“实例”而不是“类”。

You could also use 'bop': @myfunc instead of 'bop': => @myfunc() to pass along any arguments:)您也可以使用'bop': @myfunc而不是'bop': => @myfunc()传递任何 arguments :)

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

相关问题 使此关键字引用实例而不是窗口对象 - Make this keyword refer to instance rather than window object 使用object literal而不是switch语句 - Using object literal rather than switch statement javascript类实例对象字面量 - javascript class instance object literal 将小部件对象状态存储到ipython内核对象实例而不是对象类 - Store widget object state to an ipython kernel object instance rather than the object class 在Javascript中,为什么实例或对象文字没有“原型”属性? - In Javascript, why is there no “prototype” property for an instance or object literal? 为什么将数据存储在JSON中而不是JavaScript对象文字/初始化程序中? - Why store data in JSON rather than JavaScript object literal/initializer? 将对象文字升级到ScalaJS中的适当类实例? - Upgrade object literal to proper class instance in ScalaJS? 从Javascript类中的静态方法引用成员函数的正确方法 - Correct way to refer to a member function from a static method in a Javascript class 为什么 `innerHTML` 属性属于 JavaScript `Element` class 而不是 `HTMLElement`? - Why is the `innerHTML` property owned by the JavaScript `Element` class rather than `HTMLElement`? 应用于对象属性的是变量的值,而不是变量名 - Applying to an object property, the value of a variable, rather than the variable name
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM