Why does the following statement:
(function(){ console.log(this); }).apply(String("hello"));
display the following output
String {0: "h", 1: "e", 2: "l", 3: "l", 4: "o", length: 5}
and not a simple:
hello
Is this behavior built-in to the interpreter or is there a way to detect the type of reference passed?
I've always been told that when debugging an application, JavaScript's console. log() method is preferred over simply using an alert() method.
The console. log() method outputs a message to the web console. The message may be a single string (with optional substitution values), or it may be any one or more JavaScript objects.
Here's a quick lesson for you: In your web browser's devtools, your console. log() does not capture the objects you print when you print them. It captures it when you look at the printout.
console. log() is a function used to print information to the console. return on the other hand is a call to pass some value back up to where the call was made. For instance, let's say you create a function called square() that takes in a single numeric parameter and returns that value squared.
The reason that you get an object and not a string as the output of your function is that by default javascript 'this' object is always forced to be an object.
If you however use javascript in a strict format with 'use strict' then this is disabled and you can get the result that you would expect.
// wrapped in a function to allow copy paste into console
(function() {
'use strict';
(function(){ console.log(this); }).apply(String("hello"));
})();
A more thorough explanation about 'strict mode' and why it removes the boxing of this into an object can be found on the mozilla site here
In JavaScript, this
can't be a primitive type; you would need to use .valueOf()
to fetch the primitive value, i.e.:
(function(){ console.log(this.valueOf()); }).apply(String("hello"));
Or use 'use strict';
like DeadAlready mentioned in his answer.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With