我知道如果你想检查是否定义了变量a
,你可以这样做
if (typeof a !== 'undefined') {
// the variable is defined
}
但是如果你想用它来创建一个函数,比如这个
function checkDefined(name) {
return typeof name !== 'undefined';
}
checkDefined("a");
这不起作用,但如果我必须传递变量名的字符串版本,我怎么能让它工作?
由于
答案 0 :(得分:1)
签入全局范围(窗口):
var a = 'test';
var b = function() {};
function checkDefined(name) {
return typeof this[name] !== 'undefined';
}
console.log(checkDefined("a"));
console.log(checkDefined("b"));
console.log(checkDefined("c"));

如果要检查是否在类对象中声明了变量或函数,则应将新上下文传递给checkDefined方法:
function MyCustomClass() {
this.c = 'test';
}
function checkDefined(name) {
return typeof this[name] !== 'undefined';
}
// Create new object of type MyCustomClass
var myCustomClassObject = new MyCustomClass();
// In this way you can check if variable/function is defined in object
console.log(checkDefined.apply(myCustomClassObject, ["a"]));
console.log(checkDefined.apply(myCustomClassObject, ["b"]));
console.log(checkDefined.apply(myCustomClassObject, ["c"]));

apply将立即调用一个函数,让你指定this的值和函数将接收的任何参数
答案 1 :(得分:1)
受此answer的启发。我认为您可以尝试使用 eval 返回:
function checkDefined(name) {
return eval("typeof " + name) !== 'undefined';
}
示例:强>
var a = 1;
checkDefined("a") // true
checkDefined(a) // true
checkDefined("b") // false
答案 2 :(得分:0)
您还应传递需要检查变量是否已定义的对象上下文。如果它的全局传递窗口对象
function checkDefined(name, ref) {
if(!ref) {
ref = window;
}
return !!ref[name]
}
checkDefined("a"); //false if already not defined
var obj = { a: 1, b:2};
checkDefined("a",obj);//true
答案 3 :(得分:0)
局部变量是当前作用域this
对象的属性。
const log = output => document.querySelector('pre')
.innerText += output + '\n'
/* In this example, running in the browser, `this` points to `window`, but
in other environments would still point to whatever is the global object.
Bind `this` to the ``checkDefined` so to ensure it keeps the same value
as where you are calling from. */
const checkDefined = function chkDef(v) {
return typeof this[v] !== 'undefined'
}.bind(this)
a = 5
log(checkDefined('a'))
log(checkDefined('b'))
/* This is the same basic idea, but we make it a little more portable by
not binding until right before we use it, so `this` has the correct
scope. */
unboundCheckDefined = function chkDef(v) {
return typeof this[v] !== 'undefined'
}
newScope()
function newScope() {
c = 5
const checkDefined =
unboundCheckDefined.bind(this)
log(checkDefined('a'))
log(checkDefined('b'))
log(checkDefined('c'))
}
<pre></pre>