1

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

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() 而不是在 call 方法中它找不到 priv2Method 方法。即使builders对象确实将priv2Method显示为它的原型的属性。

希望有人可以在这里有所启发。

4

1 回答 1

1

Your call function is not a private method, there is no such thing in JavaScript so there is no such thing in CoffeeScript.

A more accurate description of call would be:

a function that is only visible inside the builders class.

Defining call with => creates something the behaves like a private class method. Consider this:

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

c = new C
c.m()

If you look in the console you'll see that @ inside p is the class C itself, you'll see something in the console that looks like a function but that's all a CoffeeScript class is. That's why you see the var _this in the JavaScript. When CoffeeScript sees => and you're not defining a method, CoffeeScript uses the standard var _this = this trick to make sure the references come out right in the bound function.

Also note that your call is, more or less, a private class method so there is no builders instance and you can't call the instance method priv2Method without a builders instance.

Your privLedgeMethod method:

privLedgeMethod: =>
    call()

will work fine because call is a function (not a method), the function happens to be bound to the class but it is still just a function. Hence the lack of an @ prefix when you call(). If call was a proper class method:

@call: -> ...

then you'd call it as a class method in the usual way:

@constructor.call()

Here's a simple demo that might clarify things: http://jsfiddle.net/ambiguous/tQv4E/

于 2013-05-16T00:45:45.893 回答