10

如果有什么方法可以从内部类实例访问外部类字段,除了将外部类实例传递给内部类构造函数?

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

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”。可能吗?

4

2 回答 2

4

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

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);

输出:

子测试10

于 2012-08-27T12:13:39.877 回答
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()
于 2014-12-15T15:11:01.650 回答