self widely used in Ruby Metaprogramming .
From Ruby Metaprogramming :
Each line of Ruby code is executed inside an object - the so-called current object. The current object is also known as โme,โ because you can access it with the self keyword.
Only one object can take on the role of itself at a given time, but no object holds this role for a long time. In particular, when you call a method, the receiver becomes itself. From now on, all instances of the variables are instance variables of self, and all methods called without an explicit receiver are invoked on themselves. As soon as your code explicitly calls the method on some other object, that other object becomes itself.
For instance:
class Foo attr_reader :name def initialize(name) @name = name end
Now:
foo = Foo.new('FooBar') foo.baz #=> 'FooBar'
While in JavaScript using this keyword is powerful and unique, it does not apply to an object (like ES5 strict mode) like Ruby, as shown above. this can be of 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. Context, as in languages โโlike Ruby, C # or Java). But, like Ruby self , this cannot be set by destination at runtime. For instance:
Global context ( directly copied 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();
From the above examples, it is clear that JavaScript this not exactly the cousin of Ruby self , but they have a little pinch of similarity in their behavior.
To learn Ruby self read this further and for JavaScript this read this .