Why Does Instanceof Return False for Some Literals

Why does instanceof return false for some literals?

Primitives are a different kind of type than objects created from within Javascript. From the Mozilla API docs:

var color1 = new String("green");
color1 instanceof String; // returns true
var color2 = "coral";
color2 instanceof String; // returns false (color2 is not a String object)

I can't find any way to construct primitive types with code, perhaps it's not possible. This is probably why people use typeof "foo" === "string" instead of instanceof.

An easy way to remember things like this is asking yourself "I wonder what would be sane and easy to learn"? Whatever the answer is, Javascript does the other thing.

Why does instanceof return false for a singleton using a constructor with arguments?

You're returning an object literal with the constructor property to set to the function Simple. The internal constructor is still set to Object, so instanceof returns false.

For instanceof to return true, you need to set properties using this.property in the constructor or use prototypes, and initalize a new object using new Simple().

function Simple(x, y, z) {
var _w = 0.0;

this.x = x || 0.0;
this.y = y || 0.0;
this.z = z || 0.0;

this.Test = function () {
this.x += 1.0;
this.y += 1.0;
this.z += 1.0;

console.log("Private: " + _w);
console.log("xyz: [" + this.x + ", " + this.y + ", " + this.z + "]");
}
});
(new Simple()) instanceof Simple //true

instanceof is returning false when the value is actually an instance

To fix my issue what I did is in the packages/core package I added an export to export threejs

index.ts (@engine/core)

import * as Three from 'three';
export { Three };

Then when I need to use threejs in another package I just use the one in core like this:

@engine/objects/something.ts

import { Three } from '@engine/core';

export class CreateObject {
constructor(){
this.obj = new Three.Object3D();
}
}

Why, in JavaScript, does '3 instanceof Number' == false, but '3..method()' will call Number.prototype.method?

The literal is not coerced into an instance.

What happens internally, is that an instance is created, the value is copied to the instance and the method is carried out using the instance. Then the instance is destroyed. The literal is not actually being used to carry out the method. This "wrapper" object concept is also used with string primitives when they are used like String objects. This behavior is standard.

3 is a number literal. Not an instance of the Number type. JavaScript has a primitive number type and a native Number object.

From MDN: In contexts where a method is to be invoked on a
primitive string or a property lookup occurs, JavaScript will
automatically wrap the string primitive and call the method or perform
the property lookup.



Related Topics



Leave a reply



Submit