Search code examples
javascriptfunctionprototype

Create custom function in prototype of Boolean that return self value in Integer


I want to create a custom prototype that convert the self boolean to integer

example

let x = true;
x.toInt() // 1

I tried to create a custom prototype but I can't find the value

Boolean.prototype.testf=() => {console.log(this)}; // don't found value of true

Solution

  • You cant use arrow functions as they determine their this lexically, go with a regular function:

     Boolean.prototype.toInt = function() {
       return +this;
     };