2012-08-10 54 views
0

如何在js中聲明非全局靜態方法?Javascript:我如何聲明非全局靜態方法?

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

如何調用測試功能?我是JS的新手。

感謝您的幫助。

回答

3

你可能想的對象。

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

然後,例如,撥打foo.bar.testing()

1

你可以這樣做:

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(); 
+0

爲什麼我們需要for.bar =(函數(){} .....());它似乎讓事情變得複雜 – 2012-08-10 04:05:56

+0

** @ Kit Ho **這是一個自我執行的函數,它創建一個單例。如果你在JavaScript中使用「類」或原型,請檢查我的答案我相信這就是你所說的靜態方法。 – elclanrs 2012-08-10 04:09:00

1

您是不是要找:

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


foo.bar.testing(); 
foo.bar.testing2(); 
0
// 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 
相關問題