Skip to content

Instantly share code, notes, and snippets.

@jbpotonnier
Last active December 14, 2015 01:38
Show Gist options
  • Save jbpotonnier/5007125 to your computer and use it in GitHub Desktop.
Save jbpotonnier/5007125 to your computer and use it in GitHub Desktop.
Override method in JavaScript
var create = function (proto) {
var F = function () {};
F.prototype = proto;
return new F();
};
var Point = {};
Point.initialize = function (x, y) {
this.x = x;
this.y = y;
return this;
};
Point.asString = function () {
return this.x + '@' + this.y;
};
function newPoint (x, y) {
return create(Point).initialize(x, y);
}
var Circle = create(Point);
Circle.initialize = function(x, y, radius) {
Point.initialize.call(this, x, y);
this.radius = radius;
return this;
};
Circle.asString = function () {
return 'radius: ' + this.radius + ' ' + Point.asString.call(this);
};
function newCircle (x, y, radius) {
return create(Circle).initialize(x, y, radius);
}
var p = newPoint(12, 34);
console.log(p.asString());
var c = newCircle(3, 5, 78);
console.log(c.asString());
var create = function (proto) {
var F = function () {};
F.prototype = proto;
return new F();
};
var Module = function () {
var Point = {};
var privateTo_s = function () {
return this.x + '@' + this.y;
};
Point.initialize = function (x, y) {
this.x = x;
this.y = y;
return this;
};
Point.asString = function () {
return privateTo_s.call(this);
};
return {
newPoint : function (x, y) {
return create(Point).initialize(x, y);
}
}
}();
var p = Module.newPoint(12, 34);
console.log(p.asString());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment