
-----------------------------------
wtd
Mon Apr 30, 2007 1:00 am

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.

-----------------------------------
richcash
Mon Apr 30, 2007 3:52 pm

Re: Javascript TYS
-----------------------------------
Is it like this?





function Foo() {
	bar = function() {
		return "bar"
	}
	this.baz = function(str) {
		return bar() + str
	}
}
//object example
something = new Foo()
document.write(something.baz("s"))





-----------------------------------
wtd
Mon Apr 30, 2007 9:02 pm

RE:Javascript TYS
-----------------------------------
Close, but you're missing one keyword, and the HTML was unnecessary.

-----------------------------------
wtd
Mon Apr 30, 2007 9:17 pm

RE:Javascript TYS
-----------------------------------
For bonus points, explain the concept that permits a "private" method to be created in the manner you did.

-----------------------------------
richcash
Mon Apr 30, 2007 10:22 pm

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 :
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
document.write(bar()) will actually work outside of the Foo class.

-----------------------------------
wtd
Mon Apr 30, 2007 11:04 pm

RE:Javascript TYS
-----------------------------------
Yes, that's scoping.  

Now, explain why "bar" is private in the following.

function Foo() {
   var bar = function() {
      return "bar"
   }

   this.baz = function(str) {
      return bar() + str
   }
} 

-----------------------------------
md
Tue May 01, 2007 11:52 am

RE:Javascript TYS
-----------------------------------
Scope would make bar local to Foo, and thus "private".
