CoffeeScript:从内部类实例访问外部类对象

时间:2012-08-27 11:39:52

标签: coffeescript

如果有任何方法从内部类实例访问外部类字段,EXCEPT将外部类实例传递给内部类构造函数?

更具体地说,我有一个简单的例子:

class Test
  constructor: (@number) ->

  class SubTest
    constructor: (@name) ->

    toString: () ->
      console.log @name, @number

  getSubTest: () ->
    return new SubTest "SubTest"

test = new Test 10
test.getSubTest().toString() # SubTest undefined

所以,我想得到“SubTest 10”而不是“SubTest undefined”。有可能吗?

2 个答案:

答案 0 :(得分:3)

好消息!事实证明,如果你自己创建了@的闭包,它就可以正常工作:

class Test
  self = []
  constructor: (@number) ->
    self = @

  class SubTest
    constructor: (@name) ->

    toString: () ->
      @name + self.number

  getSubTest: () ->
    return new SubTest "SubTest"

test = new Test 10
v = test.getSubTest().toString()

alert v

转换为:

var Test, test, v;

Test = (function() {
  var SubTest, self;

  self = [];

  function Test(number) {
    this.number = number;
    self = this;
  }

  SubTest = (function() {

    function SubTest(name) {
      this.name = name;
    }

    SubTest.prototype.toString = function() {
      return this.name + self.number;
    };

    return SubTest;

  })();

  Test.prototype.getSubTest = function() {
    return new SubTest("SubTest");
  };

  return Test;

})();

test = new Test(10);

v = test.getSubTest().toString();

alert(v);

输出:

<强> SubTest10

答案 1 :(得分:1)

这是一个老问题,但如果需要外部类的多个实例(如@ costa-shapiro所指出的那样),则接受的答案不起作用。这是使用内部类创建闭包的另一种方法。

SubTest = (test) ->
  class SubTest
    constructor: (@name) ->

    toString: () =>
      console.log @name, test.number

class Test
  constructor: (@number) ->
    @SubTest = SubTest @

  getSubTest: () =>
    return new @SubTest "SubTest"

test = new Test 10
test.getSubTest().toString()