简体   繁体   中英

call a javascript prototype object method from main class

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.

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();
};

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.

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM