Last active
April 6, 2020 22:01
-
-
Save mayakraft/8e3a88c4629aa3ca40501740fdcd61ec to your computer and use it in GitHub Desktop.
instanceof custom object
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!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