How 'this' in javascript is similar to 'self' in ruby

When you read or learn something new, you always try to find a correlation of new knowledge to something you already knew. So when I learned how ‘self’ changes in a ruby program, I couldn’t help but notice similarity to ‘this’ in javascript. In both ruby and javascript, ‘self’ and ‘this’ refer to the current object. Both ‘self’ and ‘this’ are transient and change depending upon the context.

Lets consider an example of ‘self’ in ruby first.

class MyExample
 def say_hello
    puts self
 	puts "Hello there."

#calling the function
my_example_obj =

Here we have defined a simple class MyExample, which has an instance method say_hello. Then we create an instance of the class and call say_hello on it. Upon invocation of instance method, ‘self’ is changed to my_example_obj and therefore it prints signature of my_example_obj followed by “Hello there.”

"Hello there."

Now lets see how an equivalent javascript handles ‘this’.

var MyExample = function(){

MyExample.prototype = {
	'say_hello' : function(){
		console.log("Hello there.");

var my_example_obj = new MyExample();

Here we have defined a simple class MyExample just like our ruby program and have defined say_hello method which gives us insight about ‘this’. And similar to ‘self’ in our ruby program, in javascript ‘this’ changes to the object, the method was called on and hence we get the following output.

MyExample /*the value of 'this'*/
"Hello there."

It is interesting to see how different languages solve certain problems. And due to fundamental similarities in concept, i.e. dynamic nature of javascript, ruby. They have similar concept of ‘this’ and ‘self’ in method invocation on objects.

« Where to find people to validate your MVP? Fixing utf8 encoding issue in Postgres »

Want articles and awesome free goodies sent directly to your inbox?

I won't spam you, promise! Unsubscribe at any time.

Enjoyed the article? Follow me on Twitter.