在 Boolean 原型中创建自定义函数,return 自身值为 Integer
Create custom function in prototype of Boolean that return self value in Integer
我想创建一个将自布尔值转换为整数的自定义原型
例子
let x = true;
x.toInt() // 1
我尝试创建自定义原型,但找不到值
Boolean.prototype.testf=() => {console.log(this)}; // don't found value of true
你不能使用箭头函数,因为它们在词法上确定它们的 this
,使用常规函数:
Boolean.prototype.toInt = function() {
return +this;
};
arrow-function
实际上使用当前封闭上下文,在您的代码中使用对象 window
作为上下文。
An arrow function expression has a shorter syntax than a function expression and does not have its own this, arguments, super, or new.target.
请改用 function declaration
or function expression
。
Boolean.prototype.toInt = function() {
console.log('' + this);
};
let x = true;
x.toInt();
let y = false;
y.toInt();
我想创建一个将自布尔值转换为整数的自定义原型
例子
let x = true;
x.toInt() // 1
我尝试创建自定义原型,但找不到值
Boolean.prototype.testf=() => {console.log(this)}; // don't found value of true
你不能使用箭头函数,因为它们在词法上确定它们的 this
,使用常规函数:
Boolean.prototype.toInt = function() {
return +this;
};
arrow-function
实际上使用当前封闭上下文,在您的代码中使用对象 window
作为上下文。
An arrow function expression has a shorter syntax than a function expression and does not have its own this, arguments, super, or new.target.
请改用 function declaration
or function expression
。
Boolean.prototype.toInt = function() {
console.log('' + this);
};
let x = true;
x.toInt();
let y = false;
y.toInt();