我想我使用了错误的术语,但这是我想做的。使用像这样的函数:
function isNumeric(){
if (isNaN(this)) { return false; }
var x = parseFloat(this);
return (x | 0) === x;
};
我知道此功能无法按原样运行。我删除了最初传入的参数,并在函数内部将其替换为 this。我想这样调用它:
var tmp1 = 10;
var tmp2 = "10";
if( tmp1.isNumeric() == true && tmp2.isNumeric() == true ){
...
}
代替这个:
if( isNumeric(tmp1) == true && isNumeric(tmp2) == true ){
...
}
最佳答案
实现该目标的方法不被认为是一个好的选择,但它是 modify the prototype chain对于您希望函数使用的数据类型,例如对于像您的示例一样的数字和字符串,您可以:
Number.prototype.isNumeric = String.prototype.isNumeric = function() {
// ...
}
您当前拥有的是首选选项,因为它不会污染内置类型的原型(prototype)链、与其他库发生冲突的风险、可能覆盖您不知道存在的功能等。您可能会遇到类似的问题:
class Val {
constructor(value) {
this.value = value;
}
isNumeric() {
if (isNaN(this.value)) { return false; }
var x = parseFloat(this.value);
return (x | 0) === x;
}
}
像这样使用:
var tmp1 = new Val(10);
var tmp2 = new Val('10');
console.log(tmp1.isNumeric(), tmp1.isNumeric());
关于Javascript 使用点表示法针对变量运行函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41434111/