2014-09-04 73 views
0

是否有任何方法爲所有類定義全局方法?爲所有類定義全局方法

更容易使用代碼來描述它...

Class.myMethod(){} 

var Foo = function(){} 
var Bar = function(){} 

Foo.myMethod(); 
Bar.myMethod(); 

我知道,它的奇怪,但我需要它。

如果it's可能的話,我怎麼能得到類變量的方法代碼:

Class.myMethod(){ 
    var anything; //anything should contains current class. 
} 

var Foo = function(){} 
var Bar = function(){} 

Foo.myMethod(); // anything should be Foo 
Bar.myMethod(); // anything should be Bar 
+2

Function.prototype.methodName =函數(){//你的函數} – Sunand 2014-09-04 14:02:05

回答

0

有沒有「階級」在Javascript。然而,FooBar是構造函數,即它們是函數,並且繼承自Function.prototype object。所以,你可以做

Function.prototype.myMethod = function(){ 
    var anything = this; // refers to the current constructor function 
    console.log(anything.name); // for example 
} 

function Foo(){} 
function Bar(){} 

Foo.myMethod(); // "Foo" 
Bar.myMethod(); // "Bar" 
+0

完美。我嘗試使用Function.method,現在與您的答案一起工作。謝謝。 – muit 2014-09-04 16:49:31