i read instanceof answer,but i have a question When i code
["a","b"] instanceof Array
why it reutrns true as the same as
new Array("a","b") instanceof Array
while
"a" instanceof String
returns false not as the same as
new String("ab") instanceof String
? very appreciate for your answers and help!
-
so you're asking what instance is "a"?No Idea For Name– No Idea For Name2013年08月07日 10:05:50 +00:00Commented Aug 7, 2013 at 10:05
3 Answers 3
For strings, you have both
- primitive strings (the ones you manipulate most of the times, and that you get from literals)
- and instances of the
Stringclass.
And they're not the same.
Here's what the MDN says on the distinction between both.
Another way to see the difference, which the MDN doesn't point, is that you can add properties on objects :
var a = "a";
a.b = 3; // doesn't add the property to a but to a wrapped copy
console.log(a.b); // logs undefined
a = new String("a");
a.b = 3;
console.log(a.b); // logs 3
(remember that most of the times, you should use primitive strings)
For arrays, you only have arrays, there is nothing like a primitive array.
1 Comment
The instanceof check is defined as:
When the [[HasInstance]] internal method of F is called with value V, the following steps are taken:
- If V is not an object, return false.
- Let O be the result of calling the [[Get]] internal method of F with property name "prototype".
- If Type(O) is not Object, throw a TypeError exception.
- Repeat
- Let V be the value of the [[Prototype]] internal property of V.
- If V is null, return false.
- If O and V refer to the same object, return true.
So string fails the very first step because string is not an object. Also note that new String doesn't return a string but an object constructed from a constructor called String. This is one example how Java and Javascript is completely different.
Here is also code for a custom instanceOf, make it work however you like then:
function instanceOf(F, V) {
if( typeof F !== "function" ) {
throw new Error( "F must be a constructor" );
}
if( Object(V) !== V ) {
return false; //not an object
}
var O = F.prototype;
if( Object(O) !== O ) {
throw new Error( ".prototype must be an object" );
}
while( true ) {
V = Object.getPrototypeOf(V);
if( V == null ) {
return false;
}
if( V === O ) {
return true;
}
}
}
2 Comments
F with property name "prototype", you just do F.prototype. [[Get]] Operation is also explained separately in the specification.In your case
"a"
is not a String Object, it is a String literal or as it is called a "primitive".
So JS is not betraying you, claiming, that "a" is not an instance of String.
CF MDN on String