Skip to content

Instantly share code, notes, and snippets.

@kdonald
Created July 6, 2011 16:46
Show Gist options
  • Save kdonald/1067723 to your computer and use it in GitHub Desktop.
Save kdonald/1067723 to your computer and use it in GitHub Desktop.
ECMAScript 5 Objects and Properties
var ns = ns || {};
ns.PropertyUtils = {
// Make the named (or all) properties of o nonenumerable, if configurable.
hide : function(o) {
var props = (arguments.length == 1)
? Object.getOwnPropertyNames(o)
: Array.prototype.splice.call(arguments, 1);
props.forEach(function(p) {
if (!Object.getOwnPropertyDescriptor(o, p).configurable) return;
Object.defineProperty(o, p, { enumerable: false });
});
return o;
}
}
ns.Point = (function() {
function Point(x, y) {
this.x = x;
this.y = y;
Object.freeze(this);
}
Point.prototype = ns.PropertyUtils.hide({
constructor: Point,
add: function(other) {
return new Point(this.x + other.x, this.y + other.y);
},
isEqualTo: function(other) {
return this.x == other.x && this.y == other.y;
}
});
return Point;
}());
var point1 = new ns.Point(3, 1);
var point2 = new ns.Point(2, 4);
point1.x = 2;
show(point1);
show(point2);
show(point1.add(point2));
for (prop in point1) {
print(prop);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment