this
In Ruby, everything is an object. That means that every bit of information and/or code can be given it’s own properties (instance variables) and actions (methods). In JavaScript, almost everything is an object, but not everything is an object.
Objects in JS
Certain things can be objects (or primitive data treated as objects), but are not always objects, such as: Booleans Strings Numbers
Certain things are always objects, such as: Dates Maths Regular expressions Arrays Functions Objects (duh!)
In JavaScript, all values, except for primitive values (strings, numbers, booleans, null, and undefined), are objects.
It’s important to understand what an object is when discussing the concept of this, because in JavaScript, this is the object that “owns” the code. It is similar to ‘self’ in Ruby. Like self, this is not a variable. It is a keyword and it’s value cannot be changed. There are some differences between how this behaves in strict mode vs non-strict mode.
this in Functions
When used in a function, this is the object that owns the function. The value of this will depend on how the function is called.
In the call above, the value of this is not set by the call. If the code is not in strict mode, the value of this must always be an object and will default to the global object.
In the call above, the value of this remains at whatever it’s set to in the function. If it is not defined (as in the code above), it remains undefined. It can also be set to any value and will remain at that value.
this as an Object Method
When used in an object, this is the object itself. This is set to the object the method is called on when a function is called as a method of an object.
In the above example, when demo.f( ) is called, inside of the function this is set to the demo object. The behavior of this is not changed by how or where the function was defined. In the following example, we call the function before attaching it to the demo.f object, however, it will result in the same behavior. What matters is that the function was called from the f member of demo.
It is important to note that the most immediate member reference is what is attached to this.
In the above code, when we call the function, we call it as a method ‘c’ of the object demo.b. During the execution, this will refer to demo.b. It does not matter that the object is a member of demo; the most immediate reference is what counts.
this as a Constructor
This can also be called in a constructor. When used in an object constructor, this is a substitute for the new object and does not have a value. When the constructor is used to create an object, this will become the new object. It gets pretty complicated and I don’t fully understand it, so that will be a topic for another blog post.














