DEV Community

Cover image for This is This and Self is Self
Ronnie
Ronnie

Posted on • Edited on

This is This and Self is Self

The curriculum at Flatiron School jumps head first in JavaScript after several months of Ruby, Sinatra and Rails. It can be a little intimidating and overwhelming. I had a particularly tough time with the difference between self and this, but it turns out they're not so different after all!

Self in Ruby and this in JavaScript both give you access to the current object, however this behaves a little bit differently. First let's talk about Ruby's self. If self is located inside of an instance method, it refers to an instance of a class. For example:

class Owner

  def walk_dogs
    self.dogs {|dog| dog.mood = "happy"}
  end
end
Enter fullscreen mode Exit fullscreen mode

In this case, self is referring to an instance of the Owner class. We can walk all of an owner's dogs to make them happy.

We can also use self to define class level methods. This means that the method belongs to a class. Sticking with our owner theme:

class Owner
  def self.dog_park
    puts "I'm going to the dog park!"
  end
end 
Enter fullscreen mode Exit fullscreen mode

Calling Owner.dog_park will output "I'm going to the dog park!"

Self is also useful in debugging and comparing objects!

Now, onto JavaScript! This can be used in global and function context.

Global Context

When we use this in the global context, it refers to the global object (window object in your browser).

this.dog = "Bark!"
console.log(window.dog);
Enter fullscreen mode Exit fullscreen mode

This will log `"Bark!" into our console.

Function context is where things start to get a little bit tricky. There are several ways a function can be invoked (function, constructor, method and indirect invocation) and this works a little differently for all of them, because they each define their own context. For now, we'll just cover function and method invocation.

Function Invocation


function simple() {
console.log(this);
}

Here, this refers to our window, or global object. If we invoke simple() in our console, it will log something like this:
screenshot of window object in browser console

Method Invocation

The code below is an example of method invocation from our function context column. In the context below, this references the object that the function is being called on. Sounds familiar, right?


const owner = {
dogs: 0,
rescueDogs: function () {
return ++this.dogs;
}
}

When we call owner.rescueDogs(), we're adding to the dogs count of our owner. The rescueDogs function is a property of the owner object. This now refers to our owner object!

Constructor and Indirect invocations are a little more complicated, but we'll cover those next time!

Top comments (1)

Collapse
 
zimlearn profile image
Dr Abstract

Very nice dot! When I was young I got a tattoo of a dot on my finger as a member of secret club... now I realize I was preparing for the dot syntax! Woot.