How to use the self with object-oriented javascript and closures
When I began with object-oriented javascript, I always saw a self here and there without fully understanding what it meant.
Self?
When you see self in some object-oriented javascript, it’s just mean that the developer is using a closure that will reference the current object via a variable named self. Because self is a variable, it could be named anything else. The use of “self” as a name is a unwritten convention but it could be whatever you want.
-
// Create a cat
-
function Cat() {
-
this.theCatName = "Mistigri";
-
}
-
-
// The cat will meow later
-
Cat.prototype.meowLater = function() {
-
// I create the variable self that refers to the this (the current object)
-
var self = this;
-
-
// I create a timeout that calls the self.meow function within an anonymous function
-
/*** NOTE : You don’t always have to create an anonymous function it’s just that in
-
this case, it is required ***/
-
window.setTimeout(
-
function() {
-
self.meow();
-
}
-
, 1000);
-
}
-
// The cat meows
-
Cat.prototype.meow = function() {
-
// I can use the this expression!!!
-
alert(this.theCatName + " : meow!");
-
}
-
-
// I crate an object and call the meowLater() function
-
var theCat = new Cat();
-
theCat.meowLater();
Why not use the this?
Because when using closures within an object, the this in the called function (in the above example, in the meow() function) is the window object.