CoffeeScript » Methods

Methods

Objects can contain any kind of value (number, string, etc.), so… you can also include a function.

And a function within an object is called a method.

For example, all layer objects have a center() method that will position the layer in the middle of the screen.

# centers the layer horizontally and vertically
layerA.center()

An example. Take, for instance, this actor object:

someActor =
    name: "Tom Cruise"

If only has a name property, which contains a string: "Tom Cruise".

So you can ask it for its name, and that’s about it.

But this next actor has methods of dealing with situations:

notAnyActor =
    name: "Chuck Norris"
    pushup: (count) ->
        print "Push the earth down #{count} times."
    fight: (opponent) ->
        if opponent.name isnt "Jackie Chan"
            print "Take off shirt, stare down #{opponent.name} and flex muscles."
            print "Wait until #{opponent.name} has left the building."
            print "Put shirt on again."
        else
            print "Run."

The notAnyActor object contains pushup() and fight() methods. The first one takes a count argument, and the second one an opponent argument.

Ready for some action?

notAnyActor.pushup 5

» "Push the earth down 5 times."
notAnyActor.fight someActor

» "Take off shirt, stare down Tom Cruise and flex muscles."
» "Wait until Tom Cruise has left the building."
» "Put shirt on again."
Download Framer project

Calling a nonexistent method will, of course, generate an error.

someActor.fight()
The Tom Cruise object needs a stand-in