I am trying to learn how to create and use javascript properties and methods using javascript prototypes and am having a bit of difficulty.
In the following code I am trying to create a simple object called ‘radius’ that has a radius of 4 and has a method called ‘getCircumference’ which produces the circumference using the object radius’ value.
function radius()
{
this = 4;
}
function getCircumference()
{
var pi = 3.141592;
var circumference = this.value * 2 * pi;
document.write(circumference);
}
radius.prototype.circumference = getCircumference;
radius.circumference();
If someone can show me how to make this code work, and better yet, how to make this code allow the input of any radius and return the circumference each time the new method is called upon. thanks!
There are a couple of problems with your code, both technically and conceptually.
On the technical side, you can’t assign to
this. Change that line tothis.value = 4and combine it with pst’s suggestion (change the last line to(new radius()).curcumference()) and I believe your code will work as-is.Conceptually, it’s probably more useful to think of a circle as an object and as having a radius rather than thinking of the radius itself as an object. Try this: