我试图使方法“ add”扩展“ Number”对象,并编辑为其分配的变量的值。就像.push方法一样。
因此,每当我执行(可变)5.add(2)并将其登录到控制台时,它都会显示7而不是变量的原始值。
我看到 .push 方法的更改是变量的值, 例如:
let i = ['Hey'];
i.push('Hiya');
console.log(i); // Displays ['Hey', 'Hiya']
这就是我所拥有的:
Number.prototype.add = function(number) { // Creating the method.
if (typeof(number) == 'string') number = Number(number);
if (typeof(number) == 'object') return 'ERROR - You introduced an object.';
let finalNumber = this.valueOf() + number;
return finalNumber;
}
let ourNumber = 5; // The variable's value is a Number.
ourNumber.add(3) // Makes the number be 5 + 3 (8) now.
// EXPECTED OUTPUT
console.log(ourNumber); // This is expected to display 8 on console.
// REAL OUTPUT
console.log(ourNumber); // It displays 5 instead of 8, which is I want it to do.
我期望输出为8,但是我得到的是原始变量的值5。