JavaScript function call/apply with string

ε祈祈猫儿з 提交于 2020-01-04 11:10:26

问题


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.


回答1:


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.




回答2:


ES spec forces the this keyword to reference an object:

  1. Else if Type(thisArg) is not Object, set the ThisBinding to ToObject(thisArg).

One workaround using Object.prototype.toString:

Object.prototype.toString.call( this ) === '[object String]'

Fiddle




回答3:


To access a function's parameters, you don't use this.

Try this instead:

var fn = function(s) {
    if (typeof (s) == 'string') { // "s" is your passed parameter there.
        alert('string param');
    }
};

(Apparently, you even specified a name for the passed parameter, already).

Have a look at this tutorial for the basics about functions and parameters.




回答4:


The reason that typeof this is "object" is because this must always point to an object. Here JavaScript is implicitly coercing the string to an object. What you want instead is the primitive value of the object. Try this:

var str = "string value";

if (typeof str === "string") alert("string outside");

function fn(str) {
    var type = typeof this.valueOf();
    if (typeof str === "string") alert("string param");
    if (type === "string") alert("string this");
    else alert(type);
};

fn.call(str, str);

Hope this helps. See the demo: http://jsfiddle.net/BuZuu/



来源:https://stackoverflow.com/questions/15027763/javascript-function-call-apply-with-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!