如何从对象调用函数

时间:2015-12-26 09:27:41

标签: javascript function object

我尝试从对象Foo调用函数但它不起作用。

function Foo(){
    function bar(){
        alert("Hello!");
    }   
}

var a = new Foo();
a.bar();

4 个答案:

答案 0 :(得分:7)

您应该将该功能设置为对象的属性

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

var a = new Foo();
a.bar();

或使用prototype在对象创建之前定义它

function Foo(){}

Foo.prototype.bar = function (){
    alert("Hello!");
};

var a = new Foo();
a.bar();

答案 1 :(得分:1)

除了@ user3896501的回答,

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);

答案 2 :(得分:0)

function Foo()
{
    // ...
}

Foo.prototype.bar = function ()
{
    alert("I called bar on a Foo object");
};

var a = new Foo();
a.bar();

答案 3 :(得分:0)

 function Foo(){
    function bar(){
       alert("Hello!");
      }   
   return {
      bar : bar
   }
}

var a = new Foo();
a.bar();