Reputation: 53
I see many people using the "this" keyword in an object oriented context in JavaScript. Similar to how "self" is used in Python and some other languages. In an object oriented context, I have been able to avoid using "this" by using the "module pattern".
For example:
var robot = (function() {
// private variables
var status = "on";
var name;
// private function
function turnOff() {
status = "off";
}
// public function
function setName(new_name) {
name = new_name;
}
return {
setName: setName
};
})();
Or, this pattern:
var robot = function(robot_name) {
// private variables
var status = "on";
var name = robot_name;
// private function
function turnOff() {
status = "off";
}
// public function
function setName(new_name) {
name = new_name;
}
return {
setName: setName
};
};
var FooBot = new robot('Foo');
var BarBot = new robot('Bar');
Is using "this" just a preference? Or, am I missing out on something?
Upvotes: 0
Views: 81
Reputation: 288080
No, this
is not a preference. this
is useful to know on which object your function was called.
In your example you don't need this information, that's why this
is not useful for you.
But consider a constructor with multiple instances, and each one has its own associated data:
class Robot {
constructor(name) {
this.status = "on";
this.setName(name);
}
turnOff() {
this.status = "off";
}
setName(new_name) {
this.name = new_name;
}
}
var robotFoo = new Robot('foo');
var robotBar = new Robot('bar');
How would you read and store the data of the desired instance without using this
?
You could use static methods and pass the instance as an argument, but that would be uglier.
Upvotes: 3