Reputation: 25
var log = function (e, clear) {
if (clear === true) {
this.clear();
}
console.log(e);
};
log.prototype = {
clear: function () {
console.clear();
}
};
i'm calling like this.
log('hi', true);
it says clear is undefined. I also tried log.clear(); but same undefined.
Upvotes: 1
Views: 434
Reputation:
Simply putting a breakpoint on the this.clear()
, or even just examining this
in the console when the error terminated script execution, would have shown you that this
was not set correctly.
The classic technique for defending against constructors not being called with new
is
if (!(this instanceof log)) { return new log(e, clear); }
Minor point, but clear === true
is semi-redundant. Boolean variables are themselves test conditions, without being compared to true
or false
.
Upvotes: 1
Reputation: 135357
I'd write it like this
function Log(e, clear) {
// make `new` optional
if (!(this instanceof Log)) {
return new Log(e, clear);
}
// clear?
if (clear === true) {
this.clear();
}
// log
console.log(e);
}
Log.prototype.clear = function clear() {
console.clear();
};
Upvotes: 3
Reputation: 239573
When you invoke a function, without new
operator, this
will refer the default global object (in browsers window
object), where clear
function is not defined. That is why you are getting this error.
To make this
refer an object created from the log
constructor function, you need to call it like this.
new log("Error", true);
Now, JavaScript creates an Object and this
will refer that newly created object. And when you do this.clear
, it will first check if the current object has clear
method, which it doesn't have. So, it will go up the prototype chain to find it in log
's prototype and that function will be executed.
Upvotes: 1