I was looking into the prototype object, and i am a bit confused about the following
//my constructor function
function Circle(r) {
this.radius = r;
this.PI = 3.14;
}
function areaCalculator() {
this.area = this.PI * this.radius * this.radius;
}
function circumferenceCalculator() {
this.circumference = 2* this.PI * this.radius;
}
since our function is an object and has a property called prototype, it is possible to add properties and methods to this prototype object and these would automatically be available for all our custom objects we create using our function constructor.
Circle.prototype.areaCalculator = areaCalculator; //adding function
Circle.prototype.color = "Red"; //adding property
var circle1 = new Circle(5);
circle1.areaCalculator();
console.log(circle1.radius);//5
console.log(circle1.area); //78.5
console.log(circle1.color);//Red
If I understand correctly, all objects using Circle will reference the same color variable unless they are explicitly set. Is this correct?
Also what does it mean to do something like below without using prototype
Circle.circumferenceCalculator = circumferenceCalculator;
Circle.color = "Red";
Are the above two statements correct?
Yes, all the objects created with
new Circlewill point to the samecolorproperty. This property will actually be located on the prototype object, not on the object that you have created. Thus, when you set it on a specific object, it will “shadow” the property from the prototype, but not overwrite it – you can try todelete obj.colorafter you set it and you’ll get the old color back.Doing
Circle.color='red'will simply set thecolorproperty on theCircleobject (even functions are objects, but they have acallableproperty which defines their behaviour when called) – this is in no way connected to theCircle‘s prototype.