I'm aware there have been a few other questions on this topic, but none of them seem to give a conclusive answer.
I'm building a HTML/CSS/JS mobile app, and have been trying the following style of notation to define some classes:
Style A
var Thing = (function ()
{
var _instance;
var _firstName;
var _lastName;
function Thing(firstName, lastName)
{
_instance = this;
_firstName = firstName;
_lastName = lastName;
}
Thing.prototype.getMyName = function ()
{
return _firstName + " " + _lastName;
}
Thing.prototype.speak = function ()
{
return ("My name is " + _instance.getMyName());
}
return Thing;
}());
The advantages of this are:
- Member variables are encapsulated and can be referred to directly (e.g. without the
this
prefix). - I can use the
_instance
variable and therefore avoid ambiguity around the identity ofthis
. - The notation is reasonably clean and readable.
I also gave the following alternatives a try:
Style B
function Thing(firstName, lastName)
{
this._firstName = firstName;
this._lastName = lastName;
}
Thing.prototype.getMyName = function()
{
return this._firstName + " " + this._lastName;
};
Thing.prototype.speak = function()
{
return "My name is " + this.getMyName();
};
Style C
class Thing
{
constructor (firstName, lastName)
{
this._firstName = firstName;
this._lastName = lastName;
}
getMyName ()
{
return this._firstName + " " + this._lastName;
}
speak ()
{
return ("My name is " + this.getMyName());
}
}
But despite their advantages, I have found B and C difficult to work with because of problems associated with the this
keyword; that is, depending on the context of the caller this
can refer to different things within the class methods. Furthermore in both these cases, using an _instance
variable as I have in A is not possible because all members need to prefixed with this.
.
However, as pointed out in the comments, Style A does not work when multiple instances of the class are created.
What's the best way to write such classes but avoid problems with this
?