2

I try to call function from object Foo but it doesn't work.

function Foo(){
 function bar(){
 alert("Hello!");
 } 
}
var a = new Foo();
a.bar();

asked Dec 26, 2015 at 9:27
2
  • 1
    As you have declared it bar() is a local function that is only available inside of the Foo() function. Commented Dec 26, 2015 at 9:34
  • Such a basic question should not be asked as you can find so many tutorials on Internet. Commented Dec 26, 2015 at 9:35

4 Answers 4

7

you should set the function as object's property

function Foo(){
 this.bar = function (){
 alert("Hello!");
 };
}
var a = new Foo();
a.bar();

or use prototype to define it before object creation

function Foo(){}
Foo.prototype.bar = function (){
 alert("Hello!");
};
var a = new Foo();
a.bar();
answered Dec 26, 2015 at 9:28
Sign up to request clarification or add additional context in comments.

Comments

1

In addition to @user3896501's answer,

function Foo() {
 // You can define all private variables/ functions.
 function bar(callBar1) {
 alert("Hello!");
 if (callBar1)
 bar1();
 }
 // This is a private function and can be called only from inside.
 function bar1() {
 alert("Hello!!!");
 }
 // Return only those variables/ functions which needs to be made public
 return {
 bar: bar
 }
}
var a = new Foo();
a.bar();
// Trying to access private function should throw exception
try {
 a.bar1();
} catch (e) {
 console.log(e)
}
// Accessing private function using parameter
a.bar(true);

answered Dec 26, 2015 at 9:39

Comments

0
function Foo()
{
 // ...
}
Foo.prototype.bar = function ()
{
 alert("I called bar on a Foo object");
};
var a = new Foo();
a.bar();
answered Dec 26, 2015 at 9:38

Comments

0
 function Foo(){
 function bar(){
 alert("Hello!");
 } 
 return {
 bar : bar
 }
}
var a = new Foo();
a.bar();
Ingo
36.4k6 gold badges57 silver badges102 bronze badges
answered Dec 26, 2015 at 9:38

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.