【发布时间】:2013-02-08 06:46:39
【问题描述】:
我刚刚注意到,当我想将字符串作为"this" 传递时,无法在 JavaScript 函数中正确获取类型。
这是一个例子:
var str = 'string value';
if (typeof (str) == 'string') {
alert('string outside');
}
var fn = function(s) {
if (typeof (str) == 'string') {
alert('string param');
}
if (typeof (this) == 'string') {
alert('string this');
}
else {
alert(typeof(this));
}
};
fn.call(str, str);
我看到 3 条消息:"string outside"、"string param" 和 "object"。
我的目标是写一个"if" 声明"this" 是字符串。像if (typeof(this) == 'string') 这样的东西。这一个不起作用,请指出将在函数内部起作用的正确语句。
【问题讨论】:
-
结局是什么?
-
我想知道,如果“this”是字符串。我在实际代码中没有参数,只有“this”,所以别无选择。
-
您到底想达到什么目的?
this是其中的window对象。或者更好的是,为什么你需要检查this是否是一个字符串?它永远不会是一个字符串。 -
我想知道调用者是否打算传递字符串(即使现在看起来像里面有字符的对象)。
-
为什么要知道
this是一个字符串?
标签: javascript function call this apply