JavaScript函数调用/应用字符串 [英] JavaScript function call/apply with string
问题描述
我刚刚注意到,当我想将字符串作为this
传递时,无法在JavaScript函数内正确获取该类型。
下面是一个例子:
var str ='string value';
if(typeof(str)=='string'){
alert('string outside');
$ b $ 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')
。这一个不起作用,请指出正确的声明,将在该函数内部工作。
原始值嵌入为当它们用作上下文时。
来自调用函数的MDN :
lockquote
请注意,这可能不会是该方法看到的实际值:如果
方法是非严格模式代码中的函数,则将null和undefined将全局对象替换为
,并且原始值将为
如果您想知道对象是否为String类型,请使用:
var isString = Object.prototype.toString.call(str)=='[object String]';
这是解决方案 MDN建议检测对象类型。
I just noticed that, when I want to pass string as "this"
, the type cannot be obtained correctly inside a JavaScript function.
Here is an example:
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);
I see 3 messages: "string outside"
, "string param"
, and "object"
.
My goal is to write an "if"
statement that says "this"
is string. Something like if (typeof(this) == 'string')
. This one does not work, please point me to the correct statement that will work inside the function.
Primitive values are embedded as objects when they're used as context.
From the MDN on the call function :
Note that this may not be the actual value seen by the method: if the method is a function in non-strict mode code, null and undefined will be replaced with the global object, and primitive values will be boxed.
If you want to know if the object is of type String, use :
var isString = Object.prototype.toString.call(str) == '[object String]';
This is the solution the MDN recommends for object type detection.
这篇关于JavaScript函数调用/应用字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!