22 March 2015
JavaScript vs. Ruby: Methods
This week we began learning JavaScript (JS) after spending the past three weeks exclusively on Ruby. The transition has not been too bad, as the languages are surprisingly quite similar in many ways. One of the key ways the two languages differ, however, is the way in which you create methods.
Ruby
As a refresher, we'll start with Ruby. Ruby has a module-class structure that makes it a little bit different from JS. You can define a new class and then within that class you can define new methods that will be available to any instances of that class. You would do that like, so:
class Athlete
def initialize(name, number)
@name = name
@number = number
end
def change_number(new_number)
@number = new_number
p "#{@name}'s new number is #{@number}!"
end
end
kobe = Athlete.new("Kobe Bryant", 8)
kobe.change_number(24)
>>"Kobe Bryant's new number is 24!"
JavaScript
To accomplish the same thing in JS, you have to do things slightly differently. From my limited experience with JavaScript, I'd say JS is less focused on classes and more focused on individual objects and functions. Objects in JS are pretty similar to hashes in Ruby. You create an object and give it property-value pairs the same way you would create a hash in Ruby and give it key-value pairs.
So first we create the object "kobe" by making it a variable and giving it properties and property values between curly braces, much like a hash in Ruby.
var kobe = {
name: "Kobe Bryant",
number: 8
};
Next, we create a function "changeNumber" that can be used to change the number property of any object. We again declare it as a variable but this time also use the "function" keyword. The parentheses after the function contain the arguments we want the function to take, which in this case is our new_number. The word "this" represents a placeholder that makes our function easily accessible to any object, and ".number" refers to the property we want to change. (Sidenote: console.log is the JS equivalent of printing to a screen in Ruby)
var changeNumber = function(new_number){
this.number = new_number
console.log(this.name + "'s new number is " + this.number)
};
Finally, we make this generic function accessible to the "kobe" object, by making it a method of the object.
kobe.changeNumber = changeNumber;
And then call the method to get the same result as our Ruby example.
kobe.changeNumber(24);
>>"Kobe Bryant's new number is 24!"
There ya go!
Prev | Next |