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.