質問

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?

役に立ちましたか?

解決

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.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top