David Golightly wrote:
> On Mar 10, 2:05 pm, System Administrator wrote:
>> function a() { }
>>
>> typeof a //returns 'function'
>> a instanceof a //returns false
>>
>> typeof Object //returns 'function'
>> Object instanceof Object //returns true
>>
>> Can anyone explain why when BOTH 'a' and 'Object'
>> are functions,
>> a instanceof a is false
>> BUT
>> Object instanceof Object is true ?
>
> It's because all objects are instances of Object,
> including itself.
Technically it is because the - instanceof - operator returns a value
based upon whether its left hand operator has the object on its prototype
chain that is the object currently referred to by the - prototype -
property of the function object that is its right hand side operator
(exceptions are thrown if the left hand operand is not an object or the
right hand operand does no have a [[HasInstance]] method (so is not a
function)). The object referred to by the - prototype - property of -
Object - is on (at the end of) the prototype chain of all objects except
for its own (as it is the only object in javascript that can have a null
[[Prototype]] property.
However, because - instanceof - is dynamically evaluated at runtime and
the - prototype - properties of all non build-in functions can be
assigned at runtime it is not necessary that - (objectConstructedWithA
instance of A) - always be true.
> Non-Objects include:
>
> null
> undefined
> NaN
> string primitives ('foo', 'bar')
> number primitives (1, 2, 3)
Either NaN is a number primitive (along with Infinity) or undefined,
infinity and NaN are all global variables which may have their values
re-assigned at runtime but start off with the Undefined primitive value,
the positive infinity numeric primitive value and the NaN numeric
primitive values, respectively.
> boolean primitives (true, false)
>
> However, "a" is not an instanceof itself, it *is* itself. So:
The object referred to by the - prototype - property of - a - is not on
the prototype chain of a.
> var b = new a;
> b instanceof a; >>> true
> a === a; >>> true
> b === a; >>> false
>
> Also, in JS, "Object" serves not only as an object, but also
> as a generic object constructor, therefore a function. Also,
> all functions are objects. Try:
>
> var k = {}; // object literal
> k instanceof Object; >>> true
> k instanceof Function; >>> false, because k was not created via
> constructor and therefore has no prototype property
<snip>
Objects created with a constructor (with the exception of objects with
function objects on their prototype chain) do not have - prototype -
properties. So - k - not being created with a constructor has no
significance.
Richard.
|