Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting “private method” in a “public function” class using CoffeeScript

I'm doing a series of tests with classes and CoffeeScript/JavaScript. See the following code:

class Example

    someFunction = ->
        alert @getText()

    constructor: ->
        @text = 'Hello world! ;)'
        someFunction()

    getText: ->
        @text


### Instance ###
example = new Example

It's just an example, when compiling I get the error:

Uncaught TypeError: Object [object global] has no method 'getText'

You know how I can solve this problem? http://jsfiddle.net/P4Xdz/

like image 762
Caio Tarifa Avatar asked Jan 13 '23 19:01

Caio Tarifa


1 Answers

If you really want to do this sort of thing, you'll have to manually provide the correct @ (AKA this) by hand with call or apply:

constructor: ->
    @text = 'Hello world! ;)'
    someFunction.call(@)

Demo: http://jsfiddle.net/ambiguous/6KZrs/

The problem is that someFunction is not a method of any kind, it is just a simple function. If you need it to behave like a method then you have to "methodize" it manually by providing the desired @ when you call it. This (and epidemian) suggests an alternative approach: explicitly pass the object as an argument:

someFunction = (ex) ->
    console.log ex.getText()

constructor: ->
    @text = 'Hello world! ;)'
    someFunction(@)

Demo: http://jsfiddle.net/ambiguous/hccDr/

Keep in mind that there is no public or private in JavaScript and so there is no public or private in CoffeeScript. You can sort of fake it but fakery has holes and tends to require more chicanery (such as manually supplying the @ with call) to make it work. If you look at the JavaScript version of your code, you'll see that someFunction is just this:

var someFunction = function() { ... };

Just a function in a variable that is scoped to the class function, nothing more. Also keep in mind that since someFunction is local to the Example class function, it won't be visible in any way to subclasses.

like image 169
mu is too short Avatar answered Jan 15 '23 09:01

mu is too short