Skip to content

Instantly share code, notes, and snippets.

@rotexhawk
Created September 1, 2016 15:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rotexhawk/e6d0a8d90e934517d55880fe8b42b977 to your computer and use it in GitHub Desktop.
Save rotexhawk/e6d0a8d90e934517d55880fe8b42b977 to your computer and use it in GitHub Desktop.
Confused about OLOO implementation.
function Shape(x,y){
this.x = x;
this.y = y;
}
Shape.prototype.move = function(x,y){
this.x += x;
this.y += y;
}
function Circle(x,y,r){
Shape.call(this,x,y);
this.r = r;
}
Circle.prototype = Object.create(Shape.prototype);
Circle.constructor = Circle;
Circle.prototype.area = function() {
return this.r * 2 * Math.PI;
}
var shape = new Shape(1,2);
shape.move(3,4);
var circle = new Circle(3,2,4);
circle.move(1,2);
console.log(circle instanceof Shape); // true
var shape_proto = Object.getPrototypeOf(shape)
var circle_proto = Object.getPrototypeOf(circle)
console.log(Object.getPrototypeOf(circle_proto) === shape_proto); // true
// OLOO
var shape = {
init: function(x,y){
this.x = x;
this.y = y;
},
move: function(x,y){
this.x += x;
this.y += y;
}
}
var circle = Object.create(shape);
// Is this the best way to go about adding a new property.
circle.setRadius = function(r){
this.r = r;
}
circle.area = function(){
return this.r * 2 * Math.PI;
}
var circ = Object.create(circle);
circ.init(2,2);
circ.setRadius(2); // extra step. What if we had a new type, like halfCircle that had a unique property of n. +1 step.
circ.move(2,2);
circ.area();
console.log(circ instaceof shape); // error
console.log(Object.getPrototypeOf(Object.getPrototypeOf(circ)) == shape); // Do we write our own function like instanceof to recurisevly check ?
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment