【问题标题】:How to access a class method in CoffeeScript?如何访问 CoffeeScript 中的类方法?
【发布时间】:2014-11-11 18:42:01
【问题描述】:

我在此做序言: 作为一个整体,我是 CoffeeScript 和 JavaScript 原型设计的新手。

话虽如此,我正在尝试在 CoffeeScript 中创建一个类的新对象,然后调用一个 getter 来检索变量,但结果却是我得到了一个“未定义”的响应。我做错了什么,或者我应该如何处理这个问题。我是新手,正在努力遵循 KISS 标准。

class TestHandler
  constructor: ->
  testArray = []
  getTestArray: ->
    @testArray

tH = new TestHandler()
tH.testArray.push 1 #testArray returns undefined
tH.getTestArray().push 1 #getTestArray returns undefined
console.log tH.getTestArray()

【问题讨论】:

    标签: javascript coffeescript


    【解决方案1】:

    当你在 CoffeeScript 中创建一个类时,你在下面列出的每个方法都指向 prototype 属性(在本例中为 TestHandler.prototype),因此在该类的实例之间共享,但是每个其他属性都将是TestHandler 本身的成员(如果名称以 @ 开头)或作用域为 class 最终将编译为的函数的私有变量(就像您的 testArray = [] 一样)。这意味着,您的tH 不会有一个名为testArray 的属性。如果您希望它成为每个实例自己的属性,请将其放入构造函数中:

    class TestHandler
        constructor: ->
            @testArray = []
        getTestArray: ->
            @testArray
    
    tH = new TestHandler()
    tH.testArray.push 1 #now everything works
    tH.getTestArray().push 1
    console.log tH.getTestArray()
    

    一般来说,房产将降落在哪里取决于您在class 声明中的书写方式。看看这个CS代码

     class TestHandler
       constructor: ->
         @testArray = [] #1
       testArray = [] #2
       @testArray = [] #3
       getTestArray: -> #4
       testArray: [] #5
    

    以及它编译成的代码:

     var TestHandler;
    
     TestHandler = (function() {
       var testArray;
    
       function TestHandler() {
         #1 @thisArray in constructor becomes instance property accessor
         this.testArray = [];
       }
    
       #2 becomes a local variable, not available outside this function
       testArray = [];
    
       #3 becomes a "static" property
       TestHandler.testArray = [];
    
       #4 is a method that goes to the prototype, so that it can be shared with all instances
       TestHandler.prototype.getTestArray = function() {};
    
       #5 is a property that goes to the prototype and can be shared with all instances (although this shouldn't be done unless you know what you do)
       TestHandler.prototype.testArray = [];
    
       return TestHandler;
    
     })();
    

    【讨论】:

    • 那么验证一下,构造函数之外的一切都是伪静态的,但是那些静态对象可以访问类内部的动态对象吗?
    • 不完全是。一切都取决于您如何编写它。在 constructor 内使用 @ -> 实例的自己的属性(就像我在 constructor 内使用 @testArray 所做的那样)。在类中使用@ -> 静态成员。 name: -> 在类内 -> 共享方法。 name = value 在类内部 -> 私有变量,作用域为类将编译到的函数。
    • 我将更新我的答案以包含我在此评论中写的内容,以便清楚。
    • 查看您更新的代码后,我是否应该将所有类方法(例如getter)放入构造函数中?
    • 共享给实例的方法在它们的上下文中被调用。这意味着如果您执行tH.getTestArray() 方法TestHandler.prototype.getTestArray 将被调用,因为它是tH 的方法,因此可以访问其属性(其中的this 将指向tH)。我建议阅读一些关于 JavaScript 继承如何工作的论文,例如 here
    猜你喜欢
    • 1970-01-01
    • 2012-04-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-05-27
    • 1970-01-01
    • 2013-01-20
    • 1970-01-01
    相关资源
    最近更新 更多