DEV Community

Joseph Knopke
Joseph Knopke

Posted on

Self and This

The self keyword in ruby is used to access the current object, depending on the context in which it is used. For example, when used in an instance method, self refers to an instance of the class. When used in a class, self refers to the Object of whichever class it's used in. This allows for code that's easier to read and change, and also useful for debugging purposes.

The this keyword in javascript has some similarities to self in ruby, but also some key differences.

The value of this depends heavily on the context in which it is called, and also whether it is called in strict-mode or non-strict-mode. In the global context, this will refer to the global object, which is often the window object. In the context of a function, the value of this will depend on how the function is called. If the value of this is not set by the call, it will automatically default to the global object.

In the context of a Class, this is a regular object, similar to self in ruby. This can be used in the constructor function of a class, and becomes self-referential.

When the bind() method is used, this will become bound to the first argument of bind, regardless of the context in which it is used.

This seems like a more confusing keyword than self in ruby, but it is also extremely useful and important when using Javascript.

Top comments (0)