:
Function.prototype. Function.prototype Function.
- , prototype / . , , , , .
any JavaScript, ( object ).
:
function example(some, params)
{
var foo = some;
this.bar = params;
}
:
window.example('fizz', 'buzz');
, foo , 'fizz' , window.bar 'buzz'.
,
var temp = new example('fizz', 'buzz');
, foo - , 'fizz' , temp.bar 'buzz'.
:
example.prototype.baz = 'w00t';
example baz 'w00t'.
"":
example.prototype.doSomething = function(){ ... };
example doSomething, .
, ?
prototype, :
example.prototype.baz = 'new w00t';
However, if you override the instance property, only that instance will be updated :
temp.baz = 'not w00t';
Your example:
You need an object circlewith a radius:
function circle(r)
{
this.radius = r;
}
Each object circlehas a circle:
circle.prototype.getCircumference()
{
return Math.PI * 2 * this.radius;
}
Now, if you create a new circle, you can get a circle:
var c = new circle(5);
console.log(c.getCircumference());
Quick note:
defining a function on a prototype allows all instances to share a link to the same function.
If you create a function for each instance:
function temp()
{
this.func = function(){...};
}
Most likely, you will have worse performance than the ability to share a prototype function:
function temp(){}
temp.func = function(){...};