Programming C, C++, Java, PHP, Ruby, Turing, VB
Computer Science Canada 
Programming C, C++, Java, PHP, Ruby, Turing, VB  

Username:   Password: 
 RegisterRegister   
 Javascript TYS
Index -> General Programming
View previous topic Printable versionDownload TopicSubscribe to this topicPrivate MessagesRefresh page View next topic
Author Message
wtd




PostPosted: 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
Sponsor
sponsor
richcash




PostPosted: 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




PostPosted: 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




PostPosted: 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




PostPosted: 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 :
code:
objectOfFoo.bar()

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




PostPosted: 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




PostPosted: Tue May 01, 2007 11:52 am   Post subject: RE:Javascript TYS

Scope would make bar local to Foo, and thus "private".
Display posts from previous:   
   Index -> General Programming
View previous topic Tell A FriendPrintable versionDownload TopicSubscribe to this topicPrivate MessagesRefresh page View next topic

Page 1 of 1  [ 7 Posts ]
Jump to:   


Style:  
Search: