Is it possible, while creating an instance of an object, to check during the instantiation itself the type of the parameter passed to the constructor, and set one of the object's variable accordingly? This is what I'm trying to do:
function Test(num1) {
this.num1 = num1;
this.isValidNumber = (function() {
console.log(this.num1); // logs "undefined" upon instantiation
if (isNaN(this.num1)) {
return false;
} else {
return true;
}
}());
}
var testObj = new Test(5);
I want isValidNumber's value to be true or false according to the parameter passed to the constructor.
thisisn't what you think it is in the inner function. The inner function can reference the outernum1function argument directly, or you can setthisappropriately when calling the inner function by using.bind(),.call()or.apply(). Note also you can simplify (remove) the if/else block by just sayingreturn !isNaN(...);thisis window and has no propertynum1.