Last active
August 29, 2015 14:01
-
-
Save catdad/86b1e0abdeb322b7057a to your computer and use it in GitHub Desktop.
This file contains hidden or 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
//a constructor | |
function Thing(a, b, c, d){ | |
//a private constructor | |
function Thing(){ | |
//we don't care about d | |
this.d = d; | |
} | |
//a is read-only | |
Thing.prototype.getA = function(){ return a; }; | |
//b is read/write | |
Thing.prototype.getB = function(){ return b; }; | |
Thing.prototype.setB = function(newB){ b = newB; }; | |
//augment c | |
c = c.toString(); | |
//c augments the value | |
Thing.prototype.getC = function(){ return c; }; | |
Thing.prototype.setC = function(newC){ c = newC.toString(); }; | |
return new Thing(); | |
} | |
//usage | |
var myThing = new Thing(1,2,3,4); | |
myThing.a; // does not exist | |
myThing.b; // does not exist | |
myThing.c; // does not exist | |
myThing.d; // a public property | |
myThing.getA(); //return 1 | |
myThing.getB(); //return 2 | |
myThing.setB(8); | |
myThing.getB(); //return 8 | |
myThing.getC(); //return "3" | |
myThing.setC(9); | |
myThing.getC(); //return "9" | |
//caveats | |
myThing instanceof Thing; //false, but expectation is true | |
myThing.constructor.name; //"Thing" -- this is because we used the same name |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment