Skip to content Skip to sidebar Skip to footer

Preventing Javascript Function From Accidentally Using The Global Window

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; th

Solution 1:

You can check to see if this is instanceof Person

varPerson = function (firstName, lastName) {
    if (!(thisinstanceofPerson))
        throw"Person constructor called without \"new\"."this.firstName = firstName;
    this.lastName = lastName;
};

Or have it recall the constructor appropriately.

varPerson = function (firstName, lastName) {
    if (!(thisinstanceofPerson))
        returnnewPerson(firstName, lastName)
    this.firstName = firstName;
    this.lastName = lastName;
};

Another possibility is to have your function run in strict mode. This will cause this to be undefined in that scenario, causing a TypeError, but only in supported implementations.

varPerson = function (firstName, lastName) {
    "use strict";
    this.firstName = firstName;
    this.lastName = lastName;
};

Post a Comment for "Preventing Javascript Function From Accidentally Using The Global Window"