Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript function call/apply with string

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.

like image 256
Tengiz Avatar asked Dec 05 '25 05:12

Tengiz


1 Answers

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.

like image 53
Denys Séguret Avatar answered Dec 06 '25 20:12

Denys Séguret



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!