Computer Science Canada Javascript TYS |
Author: | wtd [ Mon Apr 30, 2007 1:00 am ] |
Post subject: | Javascript TYS |
Write a class Foo with private method bar that returns a string "bar". It should also have a public method baz that returns the result of bar, plus a string it takes as its solitary argument. |
Author: | richcash [ Mon Apr 30, 2007 3:52 pm ] |
Post subject: | Re: Javascript TYS |
Is it like this? answer? wrote: <html>
<body> <script type="text/javascript"> function Foo() { bar = function() { return "bar" } this.baz = function(str) { return bar() + str } } //object example something = new Foo() document.write(something.baz("s")) </script> </body> </html> |
Author: | wtd [ Mon Apr 30, 2007 9:02 pm ] |
Post subject: | RE:Javascript TYS |
Close, but you're missing one keyword, and the HTML was unnecessary. |
Author: | wtd [ Mon Apr 30, 2007 9:17 pm ] |
Post subject: | RE:Javascript TYS |
For bonus points, explain the concept that permits a "private" method to be created in the manner you did. |
Author: | richcash [ Mon Apr 30, 2007 10:22 pm ] | ||||
Post subject: | Re: Javascript TYS | ||||
I missed the "var' keyword, it should be before bar. What I did was I created a global variable bar(). So when you go :
it doesn't work, and it seems as if though bar() is private. But it's not, it's just that it doesn't belong to Foo or any of Foo's objects, it is global. Which means
|
Author: | wtd [ Mon Apr 30, 2007 11:04 pm ] | ||
Post subject: | RE:Javascript TYS | ||
Yes, that's scoping. Now, explain why "bar" is private in the following.
|
Author: | md [ Tue May 01, 2007 11:52 am ] |
Post subject: | RE:Javascript TYS |
Scope would make bar local to Foo, and thus "private". |