Got a question I don't understand, can anyone make sense of it?
Question from an online resource paper:
Create javascript so that the following methods
produce the output listed next to them.
circle = new Circle();
console.log(circle.get_area()); // 3.141592653589793
circle.set_radius(10);
console.log(circle.get_area()); // 314.1592653589793
console.log(circle); // the radius of my circle is 10 and its area is 314.1592653589793
Can anyone understand what is being asked?
Here is a copy of my comment below in pretty format:
function Circle() {
this.pi=3.141592653589793;
this.radius;
}
Circle.prototype={
get_area: function(){
return this.radius*this.pi;
},
set_radius: function(radius){
return this.radius=radius;
}
};
circle开发者_开发知识库=new Circle();
circle.set_radius(100);
Okay I've played around with this and kind of get the gist of what is happening, although I'm unsure as to when or why one would need to write in this technique; if someone could explain I'd perhaps have a better understanding of its uses.
My final code is as follow: -
function Circle(r) {
this.pi=Math.PI;
}
Circle.prototype={
get_area: function(){
return this.radius*this.pi;
},
set_radius: function(radius){
return this.radius=radius;
}
};
var circle=new Circle();
circle.set_radius(100);
Circle.prototype.toString=function(){
return 'The radius of my circle is '+circle.radius+' and it\'s area is '+this.get_area();
}
console.log(circle);
I'm not entirely sure if I'm using Circle.prototype.toString=function() correctly as all it seems to do is create a string.
They're asking you to create a constructor function called Circle
which creates objects that will have get_area
, set_radius
, and toString
functions that behave in the way indicated. (toString
is what will be used in the final statement, where you're outputting the value of the circle
instance.) They're probably expecting you to give the objects those functions via the Circle
prototype (see below).
Circle
is a constructor function because it creates new objects (well, technically it just populates them; they're created by the new
operator). Sometimes people call these classes, but they're not really classes in the genuine class-based OOP way (they're constructor functions in the genuine prototype-based OOP way used by JavaScript).
There are a few ways to do this, but again, typically you'd have a Circle
function that sets up the properties for an instance on this
, and then assign functions to the Circle.prototype
, which all objects created via new Circle
will inherit. I'd dash off an example but my impression is that this is a learning exercise, so best left to the reader. But there are some pointers:
- Inside the constructor function, you can refer to the object created by the
new
operator using the keywordthis
. - The constructor function object will have a property on it called
prototype
. If you assign properties to that prototype, they'll be inherited by instances created with your constructor function (inherited through something called the prototype chain). So if I have a constructor functionFoo
, I can set a property (say,bar
) onFoo.prototype
(Foo.prototype.bar = /* whatever */;
) and all instances created vianew Foo()
will have abar
property with that value. - Functions in JavaScript are first-class objects. You can refer to them just like you can refer to strings or numbers. If I have
function foo() { /* ... */ }
, I can set a variablex
to refer to it (var x = foo;
) and then call it via that variable (x();
). - Just like
x
can refer to a function, thebar
property I mentioned above can refer to a function.
Hopefully that puts you on the right track without giving the game entirely away.
Re your comment about references for learning more about JavaScript:
- I found the book JavaScript: The Definitive Guide by David Flanagan (from O'Reilly) to be very good. It may be getting a bit dated, the fifth edition is now several years old.
- There are a bunch of articles from well-respected JavaScript guru Douglas Crockford at http://javascript.crockford.com, but I warn you that Crockford is terse. :-) Smart and informed, though, even if one doesn't always agree with his conclusions.
- I really don't like to refer to my blog [because A) SO is not about self-promotion, and B) "anemic" doesn't half say it] but there are a couple of posts there that I think might help.
Re my comment below: Really I can't leave this without an example, because it's just not helpful to do so. So here's an example of a constructor function and some functions associated with it:
// A constructor function called `Person`
function Person(fname, lname) {
// Within the constructor, we can refer to the new instance via `this`.
// Let's remember the names we were given.
this.firstName = fname;
this.lastName = lname;
// Now, the instance that is returned from `new Person(...)` will have
// those properties on it.
}
// Let's give the Person prototype a function that returns the person's
// full name.
Person.prototype.getFullName = function() {
return this.firstName + " " + this.lastName;
};
// Okay, let's see `Person` in action:
var p = new Person("John", "Doe");
console.log(p.firstName); // "John" -- this is referencing the property we set in the constructor
console.log(p.getFullName()); // "John Doe" -- this calls the function we get from the prototype
// `p` has the `getFullName` function because it inherits it from the
// `Person.prototype` object.
// Let's see what happens if I try to output the instance itself:
console.log(p); // Most like you get "[object Object]" or similar -- not useful!
// In that sort of situation, JavaScript will use a function called `toString`
// to get a string equivalent of the instance. (It's more complicated than that,
// but you don't want me to go into the details here.) So let's give
// `Person.prototype` a `toString` function that does something useful:
Person.prototype.toString = function() {
return this.getFullName();
};
// Note there that we're using `this` again. When a function is called through
// an object property (e.g., `p.toString()`), within the function call `this`
// refers to the object instance. `this` is an important and flexible concept
// in JavaScript and very much unlike its counterpart in (say) Java or C++,
// even though in simple situations (like this) it looks similar.
// Now let's try it:
console.log(p); // "John Doe", because the interpreter implicitly calls `toString` for you
// "Hey, wait a minute!" I hear you saying, "You didn't make a new `p`! How did it
// get the new function?!" The answer is it got it the same way it got `getFullName`:
// from `Person.prototype`. The `p` instance *refers* to the `Person.prototype`, it
// doesn't have a *copy* of it. So changes to `Person.prototype` show up in `p`
// (unless `p` overrides them, which we aren't doing in this example).
(That example uses anonymous functions, which I'm not a fan of, but I didn't want to get into the whole discussion of named functions here.)
(OT: Being picky, the person posing this question to you really should have declared the circle
variable at the very beginning: var circle;
Also, note that console.log
may not exist in all JavaScript implementations -- it's best known from Firefox+Firebug.)
You need to write the "Circle" class in javascript so that:
By default its area is PI (3.141592653....) or 22 / 7
The Radius property of the circle object would be 1 initially because area of circle = PI * R * R
Setting Radius to 10 makes the formula PI * 10 * 10 = 314.1592653....
I guess its pretty simple that now you can write the javascript code by yourself.
I guess what's being asked is implementing a toString()
function (or whatever its equivalent in JS is) for the Circle class that will look up this.get_radius()
and this.get_area()
and output a nicely formatted string: "the radius of my circle..."
You are supposed to implement javascript functions to create a Circle object with get_area() and set_radius() functions which will allow the script as shown to run.
精彩评论