unable to call a function defined by an object

Y

yawnmoth

Say I have the following:

<script>
var cat = (function() {
var name = "";

function changeName(name) {
this.name = name;
}

function talk() {
alert( this.name + " say meeow!" );
}

return function(name) {
this.name = name;
talk();
}
})();

firstCat = new cat("pursur");
//firstCat.changeName("Bill");
//firstCat.talk(); //alerts "Bill says meeow!"
</script>

Why can I call the talk() function, as defined in the cat variable /
function, from the return function (eg. privately) but not publically?

Also, setting this.name to name doesn't seem to accomplish anything.
What shared variable could I set for talk() to print out the same
value that the return function set?
 
T

taps128

yawnmoth said:
Say I have the following:

<script>
var cat = (function() {
var name = "";

function changeName(name) {
this.name = name;
}

function talk() {
alert( this.name + " say meeow!" );
}

return function(name) {
this.name = name;
talk();
}
})();

firstCat = new cat("pursur");
//firstCat.changeName("Bill");
//firstCat.talk(); //alerts "Bill says meeow!"
</script>

Why can I call the talk() function, as defined in the cat variable /
function, from the return function (eg. privately) but not publically?

Also, setting this.name to name doesn't seem to accomplish anything.
What shared variable could I set for talk() to print out the same
value that the return function set?

Why don't you try
function Cat(){
....
}

var firstCat=new Cat();
 
R

RobG

yawnmoth said:
Say I have the following:

<script>
var cat = (function() {
var name = "";

function changeName(name) {
this.name = name;
}

function talk() {
alert( this.name + " say meeow!" );
}

return function(name) {
this.name = name;
talk();
}
})();

firstCat = new cat("pursur");
//firstCat.changeName("Bill");
//firstCat.talk(); //alerts "Bill says meeow!"
</script>

Why can I call the talk() function, as defined in the cat variable /
function, from the return function (eg. privately) but not publically?

Also, setting this.name to name doesn't seem to accomplish anything.
What shared variable could I set for talk() to print out the same
value that the return function set?

I think the simplest answer is to ask you to read about closures:

<URL: http://www.jibbering.com/faq/faq_notes/closures.html >

You may also like this article on implementing public and private
members in javascript:

<URL: http://www.crockford.com/javascript/private.html >
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,755
Messages
2,569,535
Members
45,007
Latest member
obedient dusk

Latest Threads

Top