Skip to content

Instantly share code, notes, and snippets.

@mayakraft
Last active April 6, 2020 22:01
Show Gist options
  • Save mayakraft/8e3a88c4629aa3ca40501740fdcd61ec to your computer and use it in GitHub Desktop.
Save mayakraft/8e3a88c4629aa3ca40501740fdcd61ec to your computer and use it in GitHub Desktop.
instanceof custom object
<!DOCTYPE html>
<title>.</title>
<script>
// must instantiate with "new"
var Point = function (x, y) {
this.x = x;
this.y = y;
};
// "new" not needed
var Vector = function (x, y) {
var proto = {};
// this is so the "enumerable" property defaults to false
Object.defineProperty(proto, "constructor", { value: Vector });
var v = Object.create(proto);
v.x = x;
v.y = y;
return v;
};
// test instanceof
var p = new Point(1, 2);
var v = Vector(1, 2);
console.log(
p instanceof Point,
v instanceof Vector
);
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment