If I wanted to create a javascript “class” with two properties, I’d probably do something like:
var Person = function (firstName, lastName) {
this.firstName = firstName;
this.lastName = lastName;
};
I could then create a new person as follows:
var p = new Person("John", "Doe");
console.log(p.firstName + " " + p.lastName);
At this point, everything is great. However, if someone accidentally (or purposely) calls the following:
Person("Mary", "Smith"); // without "new"
All of the sudden, firstName and lastName are part of the global window context, and could potentially screw up the whole page.
console.log(window.firstName); // logs "Mary"
Is there a good way to try to prevent this, when building the Person “class”? Obviously if someone wanted to break something in javascript, they can do it, but I’m just looking for the best practice.
I could throw something like this at the top of the class, but I don’t know if that’s a good answer:
if (this === window) {
console.log("You are fail");
return;
}
You can check to see if
thisisinstanceof PersonOr have it recall the constructor appropriately.
Another possibility is to have your function run in strict mode. This will cause
thisto beundefinedin that scenario, causing a TypeError, but only in supported implementations.