When I run the following code I get told, that talk is not a function.
Why?
function cat(name) {
talk = function() {
alert(" say meeow!" )
}
}
cat("felix");
cat.talk()
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
What you’re trying to do is create an object for which the function is a constructor, but what the code is actually doing is setting the variable
talkto a function. You want:edit:
Relevant javascript tech talk: http://www.youtube.com/watch?v=ljNi8nS5TtQ
He talks about constructing objects with functions at about 30 minutes in. The code he posts is:
And the relevant quote:
In other words, he’s saying that when using the
newkeyword, you’re defining your variable as an object and calling the function in the context of that object (thispoints to your object).The extra thing that the
newkeyword does is set the prototype of the newly made object to the prototype of the constructor. So if we do:instance instanceof Circleis now true.