Rebecca Greenblatt

Girl Who Codes

Javascript: Object Orientation

I’m going to use this post to go through some of the things I find counterintuitive about Javascript’s Object Orientated design. Note: I pretty much just took Jon Grover’s slides and turned them into a blog post.

I’ll start with the fact that constructors are just functions. And if prototypes are just functions, then why do I need to use “new” before instantiating a new instance?

1
2
3
4
5
6
7
8
9
function Person(name){
  this.name = name;
  this.favorite_color = "blue";
}

var rebecca = new Person("Rebecca");

rebecca.name; // "Rebecca"
rebecca.favorite_color; // "blue"

From my understanding, the “new” tells us where to fill in the “this” references made in the constructor and also places the parent first in the prototype chain. So if I call a method on rebecca that has not been specified, the next place it will look is the Person constructor. This is why I am able to call both rebecca.name and rebecca.favorite_color, even though I did not specifically set rebecca’s favorite color.

Ok, next: what is the deal with private versus public methods? Let’s say I wanted to add a method to the Person prototype…

1
2
3
4
5
6
7
8
9
10
11
function Person(name){
  this.name = name;
  this.favorite_color = "blue";
  function greeting(){
    return "Nice to meet you";
  }
}

var rebecca = new Person("Rebecca");

rebecca.greeting(); //TypeError: undefined is not a function

I would not be able to call rebecca.greeting(); because this method would not be accessible to instances of Person. However, if we wrote it the following way, creating an instance method of ‘this.greet,’ we could call greeting inside the constructor, and then it would be accessible by instances of Person through the instance method.

1
2
3
4
5
6
7
8
9
10
11
12
13
function Person(name){
  this.name = name;
  this.favorite_color = "blue";

  function greeting(){
    return "Nice to meet you";
  }
  this.greet = function(){ return greeting() };
}

var rebecca = new Person("Rebecca");

rebecca.greet(); // "Nice to meet you"

Another way we could have done this without completely redefining the Person constructor, would be to stick with our original constructor, and add functionality for all of its instances by doing:

1
Person.prototype.greet = function(){ return "Nice to meet you"; };

and then we would have been able to call rebecca.greet with no problem. I think about it as going inside the Person constructor, and then substituting prototype.greet with this.greet.

One last oddity appears when dealing with the scope of “this” inside functions in a constructor. As an example, this would come into play if we wanted to incorporate the name of the instance in the greet method, and have rebecca.greet(); return “Nice to meet you. My name is Rebecca.” The following could would NOT work:

1
2
3
4
5
6
7
8
9
10
11
12
13
function Person(name){
  this.name = name;
  this.favorite_color = "blue";

  function greeting(){
    return "Nice to meet you. My name is " + this.name + ".";
  }
  this.greet = function(){ return greeting() };
}

var rebecca = new Person("Rebecca");

rebecca.greet(); //"Nice to meet you. My name is ."

The problem here is that once we enter the greeting function, the scope of this is no longer an instance of the Person constructor. Somehow we need to capture the scope of “this” before we enter the function…

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
function Person(name){
  this.name = name;
  this.favorite_color = "blue";

  var self = this;

  function greeting(){
    return "Nice to meet you. My name is " + self.name + ".";
  }
  this.greet = function(){ return greeting() };
}

var rebecca = new Person("Rebecca");

rebecca.greet(); //"Nice to meet you. My name is Rebecca."

This method takes advantage of javascript’s unique scoping properties. This would also work!

1
2
3
4
5
6
7
8
9
10
11
12
function Person(name){
  this.name = name;
  this.favorite_color = "blue";

  var self = this;

  this.greet = function(){ return "Nice to meet you. My name is " + self.name + "."; };
}

var rebecca = new Person("Rebecca");

rebecca.greet(); //"Nice to meet you. My name is Rebecca."

Hope this post helped clear some things up about Javascript’s prototype-based design.

SQL for Rubyists

SQL is a great tool, but for us Rubyists, it can sometimes be hard to grasp the concepts of querying a database. I’ve decided to re-write a couple of SQL queries in Ruby to remind myself of how the rows in a table correspond to an Object and its attributes.

For this example, we’ll be modeling a crowdfunding website; we have pledges, projects, and users.

  • a User has a name
  • a Project has a title, category, and funding goal
  • a Pledge has an amount and belongs to both a user and a project

If we were to imagine the database, each of these objects would have its own table.

  • the ‘users’ table would have an ‘id’ and ‘name’ column
  • the ‘projects’ table would have an ‘id,’ ‘title,’ ‘category’ and ‘funding goal’ column
  • the ‘pledges’ table would have an ‘id’, ‘user_id’, and ‘project_id’ column

For our Ruby “queries” I’ve created an Object Class for User, Project, and Pledge with these same column headers as attributes for their respective classes.

Now we are ready to start our queries! I will be writing my Ruby methods so that their output is identical to the SQLite output we would get if we ran the equivalent query in SQL.

Select the title of all projects and the total amount they have raised

SQL:

1
2
3
SELECT projects.title, SUM(pledges.amount)
FROM projects JOIN pledges ON pledges.project_id = projects.id
GROUP BY projects.title

Ruby:

1
2
3
4
5
6
7
8
9
projects.collect do |project| ##GROUP BY
  raised = 0
  pledges.each do |pledge| ##JOIN
    if pledge.project_id == project.id ##ON
      raised += pledge.amount ##SUM
    end
  end
  [project.title, raised] ##SELECT
end

OUTPUT: [[“World’s Best Book”, 300], [“World’s Worst Book”, 700], [“Save The Whales”, 1100], [“Save The Rhinos”, 500], [“Save The Fish”, 1000], [“World’s Best Album”, 800], [“World’s Worst Album”, 600]]

Select the title of all projects that have met their funding goal

SQL:

1
2
3
4
SELECT projects.title
FROM projects JOIN pledges ON pledges.project_id = projects.id
GROUP BY projects.title
HAVING SUM(pledges.amount) >= projects.funding_goal

Ruby:

1
2
3
4
5
6
7
8
9
10
11
projects.collect do |project| ##GROUP BY
  raised = 0
  pledges.each do |pledge| ##JOIN
    if pledge.project_id == project.id ##ON
      raised += pledge.amount ##SUM
    end
  end
  if raised > project.funding_goal ##HAVING
    [project.title] ##SELECT
  end
end.compact

OUTPUT: [[“Save The Whales”], [“World’s Best Album”]]

Select the names of all users and the total amount they have pledged

SQL:

1
2
3
4
SELECT users.name, SUM(pledges.amount)
FROM users JOIN pledges ON pledges.user_id = users.id
GROUP BY users.name
ORDER BY SUM(pledges.amount)

Ruby:

1
2
3
4
5
6
7
8
9
users.collect do |user| ##GROUP BY
  pledged = 0
  pledges.each do |pledge| ##JOIN
    if pledge.user_id == user.id ##ON
      pledged += pledge.amount ##SUM
    end
  end
  [user.name, pledged] ##SELECT
end.sort_by{|name, total_pledged| total_pledged} ##ORDER BY

OUTPUT: [[“Matthew”, 500], [“Jonathan”, 700], [“Rebecca”, 900], [“Jordan”, 1100], [“Melissa”, 1800]]

Select the category name and the sum total of the pledge amounts of all the pledges in the book category

SQL:

1
2
3
SELECT projects.category, SUM(pledges.amount)
FROM projects JOIN pledges ON projects.id = pledges.project_id
WHERE projects.category = 'books'

Ruby:

1
2
3
4
5
6
7
8
9
10
11
total = 0
projects.each do |project|
  if project.category == "books" ##WHERE
    pledges.each do |pledge| ##JOIN
      if pledge.project_id == project.id ##ON
        total += pledge.amount ##SUM
      end
    end
  end
end
[["books", total]] ##SELECT

OUTPUT: [[“books”, 1800]]

Another, more sophisticated Object-oriented model would be one in which each object had an attribute that explained their relationship to the other. For example, each pledge instance would have a user attribute and a project attribute. Each user would have an array of pledges they have made, and each project would have an array of pledges that were made towards their funding goal.

I hope this post helped you see SQL queries in a new way!