理想情况下,我希望能够编写如下内容:
function a( b ) {
b.defaultVal( 1 );
return b;
}
这样做的目的是,如果 b
是任何定义的值,b
将保持该值;但如果 b
未定义,则 b
将设置为 defaultVal()
的参数中指定的值,在本例中为 1
。
这可能吗?
我一直在玩弄这样的东西:
String.prototype.defaultVal=function(valOnUndefined){
if(typeof this==='undefined'){
return valOnUndefined;
}else{
return this;
}
};
但是我没有成功地将这种逻辑应用于任何变量,尤其是 undefined variable 。
有没有人对此有任何想法?可以吗?还是我找错了树?
最佳答案
为什么不使用默认运算符:
function someF(b)
{
b = b || 1;
return b;
}
工作完成!这是 more info关于它是如何工作的。
作为旁注:您的原型(prototype)将无法工作,因为您正在扩充 String
原型(prototype),而如果您的变量未定义,则 String
原型(prototype)不完全适用。
为了绝对, super 确定你只是切换到默认值,当 b
真的是未定义的时候,你可以这样做:
var someF = (function(undefined)//get the real undefined value
{
return function(b)
{
b = b === undefined ? 1 : b;
return b;
}
})(); // by not passing any arguments
关于javascript - 在javascript中为 undefined variable 设置默认值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12409813/