Idiot-proofing JavaScript "classes"
Given this JavaScript "class":
function Person(first,last)
{
this.name=first+' '+last;
}
//Instantiation
var superstar=new Person('Wayne','Rooney');
A correct instantiation (like above) will set the context for this
to be superstar
.
But what if someone (or even you) wrongly instantiate it as below?
//"new" is omitted
var genius=Person('Wolfgang Amadeus','Mozart');
Well, in that case, this
will refer to window
and you've just set or overrode window.name
. That's bad.
To prevent this, you should check if the instance of this
is that of the function, like below:
function Person(first,last)
{
if(!(this instanceof Person))
{
return new Person(first,last);
}
this.name=first+' '+last;
}
This doesn't make omitting new
right, but it does make it harmless as this
will always refer to the context it's supposed to.
Note:
Another way of doing the if-check, but in a more dynamic way, would be to use this instanceof arguments.callee
.
However, ES5
forbids use of arguments.callee
in strict mode.
Written by Francisc Romano
Related protips
Have a fresh tip? Share with Coderwall community!
Post
Post a tip
Best
#Class
Authors
Sponsored by #native_company# — Learn More
#native_title#
#native_desc#