JavaScript 函数调用/应用字符串 [英] JavaScript function call/apply with string

查看:29
本文介绍了JavaScript 函数调用/应用字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚刚注意到,当我想将字符串作为 "this" 传递时,无法在 JavaScript 函数中正确获取类型.

I just noticed that, when I want to pass string as "this", the type cannot be obtained correctly inside a JavaScript function.

这是一个例子:

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".

I see 3 messages: "string outside", "string param", and "object".

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

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.

来自关于调用函数的MDN :

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

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]';

这是MDN 推荐的解决方案 用于物体类型检测.

This is the solution the MDN recommends for object type detection.

这篇关于JavaScript 函数调用/应用字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆