如何在JavaScript中的對象上實現構造函數和命名函數?使用構造函數和命名成員創建對象
這是我想如何使用對象:
o("..."); // use the object's constructor
o.namedFunction("..."); // use a named member on the object
我不想不得不「新達」對象它可用之前......你可以說我想要的相當於有一堆靜態方法和構造函數的靜態類。
如何在JavaScript中的對象上實現構造函數和命名函數?使用構造函數和命名成員創建對象
這是我想如何使用對象:
o("..."); // use the object's constructor
o.namedFunction("..."); // use a named member on the object
我不想不得不「新達」對象它可用之前......你可以說我想要的相當於有一堆靜態方法和構造函數的靜態類。
這奏效了:
var o = function()
{
return "constructor";
};
o.namedFn = function()
{
return "namedFn";
};
console.log(o("test"));
console.log(o.namedFn("test"));
console.log(o("test"));
這個SO question有幾個很好的建議和例子。另外,創建實例/對象時一定要使用新的。
var obj = new MyClass();
obj.someMethod();
我認爲你要在你的constructor functions有靜態成員(在基於類的面嚮對象語言)。
在JavaScript函數是first-class對象,這意味着它們可以有屬性,他們可以就像任何對象進行處理:
functon Ctor (arg) {
//...
}
Ctor.namedFunction = function() {
// "static" member
};
var instance = new Ctor("..."); // use the object's constructor
Ctor.namedFunction("..."); // use a named member on the object
注意,我直接添加namedFunction
屬性到Ctor
功能對象。
這是我會怎麼做,只是爲了能夠通過封閉來分享我的方法裏面的一些屬性:
<html>
<head>
<title>so</title>
</head>
<body>
<script>
function fn(arg){
var init = arg;
return {
meth:function(arg){
alert(init + arg);
}
};
};
var obj = fn('Stack');
obj.meth('Overflow');
</script>
</body>
</html>
一些你不通過外部聲明。