Last active
December 14, 2015 01:38
-
-
Save jbpotonnier/5007125 to your computer and use it in GitHub Desktop.
Override method in JavaScript
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
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()); |
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
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