nighthawk457
nighthawk457

Reputation: 1150

prototype in javascript

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?

Upvotes: 0

Views: 239

Answers (2)

Joseph
Joseph

Reputation: 119827

A function is also an object and you can augment properties to it. A common example is jQuery, where the $ acts as both an object and a function.

function Circle(r) {}
Circle.circumferenceCalculator = circumferenceCalculator;
Circle.color = "Red";

$.each();             //$ as an object
$('selector').each()  //$ as a function

However, this won't reflect in the instance you create. The ones that reflect on the instances are only those that are added via prototype and those in the constructor function.

function Circle(r) { 
    this.radius = r;
    this.PI = 3.14;
}

Circle.prototype.areaCalculator = areaCalculator;
Circle.prototype.color = "Red";

var mycircle = new Circle(5);

//props on Circle itself:
//Circle.color
//Circle.areaCalculator

//props on the instance:
//mycircle.radius
//mycircle.PI
//mycircle.areaCalculator
//mycircle.color

Upvotes: 0

deviousdodo
deviousdodo

Reputation: 9172

Yes, all the objects created with new Circle will point to the same color property. 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 to delete obj.color after you set it and you'll get the old color back.

Doing Circle.color='red' will simply set the color property on the Circle object (even functions are objects, but they have a callable property which defines their behaviour when called) - this is in no way connected to the Circle's prototype.

Upvotes: 3

Related Questions