有多種方式:
// when using one() as a constructor for an object
function one()
{
this.abc = function() { };
this.def = function() { };
}
obj = new one();
obj.abc();
// prototype
function one()
{
}
one.prototype.abc = function() { };
one.prototype.def = function() { };
obj = new one();
obj.abc();
// module pattern
function one()
{
var abc = function() { };
var def = function() { };
return {
abc: abc,
def: def
}
}
obj = one();
obj.abc();
// or just assign it as a property to your function
function one()
{
}
one.abc = function() { }
one.def = function() { }
one.abc();
選擇任何適合你。
通常,您不會在範圍窄於您想要使用它的範圍內定義函數。 – Quentin 2014-11-24 10:55:34
使用類或名稱空間來執行此操作。 – ZiTAL 2014-11-24 11:07:06
關於javascript我建議不要嵌套許多匿名函數。如果你去嵌套函數最好給一些名稱,因爲它更容易看到堆棧和調試 – rkmax 2014-11-24 13:47:45