Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What are the differences between 'self' in ruby and 'this' in javascript

I am familiar with ruby and begin to learn javascript. Is it safe to skip to learn 'this' and consider it as a complete equivalence of ruby's 'self' in javascript and 'apply' in javascript is the same as 'instance_eval' in ruby?

If not,what are some big differences between them?

like image 797
user145055 Avatar asked Sep 30 '22 11:09

user145055


1 Answers

self is widely used in Ruby Metaprogramming.

From Metaprogramming Ruby book:

Every line of Ruby code is executed inside an object—the so–called current object. The current object is also known as self, because you can access it with the self keyword.

Only one object can take the role of self at a given time, but no object holds that role for a long time. In particular, when you call a method, the receiver becomes self. From that moment on, all instance variables are instance variables of self, and all methods called without an explicit receiver are called on self. As soon as your code explicitly calls a method on some other object, that other object becomes self.

For example:

class Foo

  attr_reader :name

  def initialize(name)
    @name = name  
  end

  # here self indicates the class itself Foo
  def self.bar
  end

  # here self indicates the instance of class Foo
  def baz
    self.name
  end
end

Now:

foo = Foo.new('FooBar')
foo.baz #=> 'FooBar'

While in JavaScript use of this keyword is powerful and unique, it does not refer to an object(as of ES5's strict mode) like Ruby as shown above. this can have any value. The value of this within any given function call is determined by how the function is called (not where the function is defined, i.e. the context, as in languages like Ruby, C#, or Java). But, similar to Ruby's self, this can't be set by assignment during execution. For example:

Global context(directly copied from here):

console.log(this.document === document); // true

// In web browsers, the window object is also the global object:
console.log(this === window); // true

this.a = 37;
console.log(window.a); // 37

or as an object method:

var foo = {};
foo.bar = function() {
  console.log(this.firstName);
};
foo.firstName = 'FooBar';
foo.bar(); // "FooBar"

From examples shown it's pretty clear that JavaScript's this isn't exactly a cousin brother of Ruby's self, but do they have a small pinch of similarity in their behaviors.

For exploring Ruby's self further read this and for JavaScript's this read this.

like image 132
Surya Avatar answered Oct 03 '22 11:10

Surya