Created
September 1, 2016 15:27
-
-
Save rotexhawk/e6d0a8d90e934517d55880fe8b42b977 to your computer and use it in GitHub Desktop.
Confused about OLOO implementation.
This file contains 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
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