JavaScript函数调用/ apply with string

Ten*_*giz 2 javascript function this call apply

我只是注意到,当我想传递字符串时"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);
Run Code Online (Sandbox Code Playgroud)

我看到3个信息:"string outside","string param",和"object".

我的目标是编写一个"if"声明"this"为字符串的语句.有点像if (typeof(this) == 'string').这个不起作用,请指出我将在函数内部工作的正确语句.

Den*_*ret 6

当原始值用作上下文时,它们作为对象嵌入.

MDN上的通话功能:

请注意,这可能不是方法看到的实际值:如果方法是非严格模式代码中的函数,则null和undefined将替换为全局对象,并且原始值将被加框.

如果您想知道对象是否为String类型,请使用:

var isString = Object.prototype.toString.call(str) == '[object String]';
Run Code Online (Sandbox Code Playgroud)

这是MDN推荐的对象类型检测解决方案.


Fab*_*tté 5

ES规范强制this关键字引用对象:

  1. 否则,如果Type(thisArg)不是Object,则将设置ThisBindingToObject(thisArg)

一种解决方法是使用Object.prototype.toString

Object.prototype.toString.call( this ) === '[object String]'
Run Code Online (Sandbox Code Playgroud)

小提琴