Javascript:如何声明非全局静态方法

Javascript: How can I declare non-global static methods?

本文关键字:全局 静态方法 声明 何声明 Javascript      更新时间:2023-09-26
如何在

js中声明非全局静态方法?

foo.bar = function() {
  function testing{
    console.log("statckoverlow rocks!");
  }
  function testing2{
    console.log("testing2 funtction");
  }
}

如何调用测试函数?我是JS的新手。

感谢您的帮助。

你可能想要一个对象。

foo.bar = {
  testing: function() {
    console.log("statckoverlow rocks!");
  },
  testing2: function() {
    console.log("testing2 funtction");
  }
};

然后,调用foo.bar.testing() ,例如。

你可以

这样做:

foo.bar = (function() {
  var testing = function () {
    console.log("statckoverlow rocks!");
  };
  var testing2 = function () {
    console.log("testing2 funtction");
  };
  return {
    testing: testing,
    testing2: testing2
  };
}());
// call them
foo.bar.testing();
foo.bar.testing2();

你的意思是:

var foo = {
    bar: {
        testing: function()
        {
            console.log("statckoverlow rocks!");
        },
        testing2: function()
        {
            console.log("testing2 funtction");
        }
    }
};

foo.bar.testing();
foo.bar.testing2();
// Constructor
function Foo() {
  var myvar = 'hey'; // private
  this.property = myvar;
  this.method = function() { ... };
}
Foo.prototype = {
  staticMethod: function() {
    console.log( this.property );
  }
}
var foo = new Foo();
foo.staticMethod(); //=> hey