简体   繁体   中英

Javascript - typeof a primitive value is an object?

Please check the fiddle - http://jsfiddle.net/n8emgLw9/

var a = [3, 6, 1, "str", 8];
$.each(a, function (i, e, x) {
console.log(this);
console.log(this + " is of type " + typeof this);
});

1) It logs as a primitive value in the first log entry, and then typeof logs as an object. Something is not right or it is a misnomer.

2) logging only "this"(first log statement) gives more details, but when logged in the second statement, it just prints the value. Why?

When you use call or apply (what $.each does behind the scenes) and pass a primitive, JS implicitly "boxes" it into a corresponding object type:

 function foo() { document.write(typeof this); document.write(Object.prototype.toString.call(this)); } foo.apply(123) 

Reference: http://ecma-international.org/ecma-262/5.1/#sec-10.4.3

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

Those are not primitives. Compare:

console.log("foo", new String("foo"));
console.log(1,     new Number(1)    );
console.log(true,  new Boolean(true));

The first values are primitives; the second ones are objects that wrap primitives (ie boxed versions).

As to why it happens, $.each is implemented in terms of Function.prototype.call , which has this bit in its documentation ( MDN ):

The value of this provided for the call to fun . 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 .

(Emphasis mine)

If you use + operator, js casts the whole thing to string.

What you probably want to use is:

console.log(this, " is of type " + typeof this);

with the comma.

Here is updated code. You may have expected this result than yours?

http://jsfiddle.net/n8emgLw9/1/

var a = [3, 6, 1, "str", 8];

for (var e in a){
    console.log(a[e]);
    console.log(a[e] + " is of type " + typeof a[e]);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM