【问题标题】:Coffeescript-Javascript correlationCoffeescript-Javascript 相关性
【发布时间】:2023-03-05 21:31:01
【问题描述】:

我试图了解如何使用 coffeescript 创建私有方法。以下是示例代码

class builders
constructor: ->
    // private method
    call = =>
            @priv2Method()
    // privileged method
    privLedgeMethod: =>
            call()
    // privileged method 
    priv2Method: =>
            console.log("got it")

下面是生成的JS代码。

(功能() { var建设者, __bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; }; 建设者=(函数(){ var 调用, _这=这; 功能建设者(){ this.priv2Method = __bind(this.priv2Method, this); this.privLedgeMethod = __bind(this.privLedgeMethod, this); } 调用 = 函数() { 返回builders.priv2Method(); }; builders.prototype.privLedgeMethod = function() { 返回调用(); }; builders.prototype.priv2Method = function() { return console.log("知道了"); }; 返回建设者; }).call(this); }).call(this);

请注意,我在函数定义中使用了“胖箭头”。有几件事我没有从代码中得到。

  1. _this 变量有什么用
  2. 如果您将此代码运行为:(new builders()).privLedgeMethod(),而不是在调用方法内部,它不会找到 priv2Method 方法。即使builders对象确实将priv2Method显示为它的原型的属性。

希望有人可以在这里提供一些启示。

【问题讨论】:

    标签: javascript coffeescript private prototypal-inheritance


    【解决方案1】:

    您的call 函数不是私有方法,JavaScript 中没有这样的东西,所以 CoffeeScript 中也没有这样的东西。

    call 的更准确描述是:

    一个仅在 builders 类中可见的函数。

    => 定义call 会创建一些行为类似于私有类方法的东西。考虑一下:

    class C
        p = => console.log(@)
        m: -> p()
    
    c = new C
    c.m()
    

    如果您查看控制台,您会看到p 中的@ 本身就是类C,您会在控制台中看到一些看起来像函数的东西,但这就是CoffeeScript 类的全部内容。这就是您在 JavaScript 中看到 var _this 的原因。当 CoffeeScript 看到 => 并且您没有定义方法时,CoffeeScript 使用标准的 var _this = this 技巧来确保引用正确地出现在绑定函数中。

    还请注意,您的 call 或多或少是一个私有 class 方法,因此没有 builders 实例,并且您不能在没有 @ 的情况下调用实例方法 priv2Method 987654337@ 实例。

    您的privLedgeMethod 方法:

    privLedgeMethod: =>
        call()
    

    可以正常工作,因为call 是一个函数(不是方法),该函数恰好绑定到类,但它仍然只是一个函数。因此,call() 时缺少 @ 前缀。如果call 是一个合适的类方法:

    @call: -> ...
    

    然后你会以通常的方式将它称为类方法:

    @constructor.call()
    

    这是一个简单的演示,可能会澄清一些事情:http://jsfiddle.net/ambiguous/tQv4E/

    【讨论】:

      猜你喜欢
      • 2013-01-24
      • 1970-01-01
      • 2023-03-11
      • 2013-10-08
      • 2011-09-17
      • 1970-01-01
      • 1970-01-01
      • 2011-08-30
      • 2016-02-14
      相关资源
      最近更新 更多