| Author |
Message |
wtd
|
Posted: 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. |
|
|
|
|
 |
Sponsor Sponsor

|
|
 |
richcash
|
Posted: 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> |
|
|
|
|
 |
wtd
|
Posted: Mon Apr 30, 2007 9:02 pm Post subject: RE:Javascript TYS |
|
|
| Close, but you're missing one keyword, and the HTML was unnecessary. |
|
|
|
|
 |
wtd
|
Posted: 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. |
|
|
|
|
 |
richcash
|
Posted: 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
| code: | document.write(bar()) | will actually work outside of the Foo class. |
|
|
|
|
 |
wtd
|
Posted: 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.
| code: | function Foo() {
var bar = function() {
return "bar"
}
this.baz = function(str) {
return bar() + str
}
} |
|
|
|
|
|
 |
md

|
Posted: Tue May 01, 2007 11:52 am Post subject: RE:Javascript TYS |
|
|
| Scope would make bar local to Foo, and thus "private". |
|
|
|
|
 |
|