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
Yaroslav Shabanov
2831 gold badge4 silver badges18 bronze badges
4 Answers 4
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
user3896501
3,0472 gold badges24 silver badges25 bronze badges
Sign up to request clarification or add additional context in comments.
Comments
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
Rajesh Dixit
25.1k5 gold badges52 silver badges86 bronze badges
Comments
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
Emad Armoun
2,1472 gold badges23 silver badges35 bronze badges
Comments
function Foo(){
function bar(){
alert("Hello!");
}
return {
bar : bar
}
}
var a = new Foo();
a.bar();
Ingo
36.4k6 gold badges57 silver badges102 bronze badges
Comments
lang-js
bar()is a local function that is only available inside of theFoo()function.