2017-06-19 59 views
0

我想在javascript中創建一個方法,它可以被每個元素使用。不需要添加像通用方法Javascript

object = { 
methodName : function(){ 

} 
}; 
+3

擴展'Object'原型,也許? –

+2

[javascript將原型方法添加到所有函數?](https://stackoverflow.com/questions/2126844/javascript-add-prototype-method-to-all-functions) – krillgar

+1

另請參閱[爲什麼要擴展原生對象一個不好的做法?](https://stackoverflow.com/questions/14034180/why-is-extending-native-objects-a-bad-practice) –

回答

0

你最好的選擇是延長Object原型。

// extend 
 
Object.prototype.myFunction = function(){ 
 
    console.log('universal Object function'); 
 
} 
 
// now every object created and instance of Object will have the method myFunction available to use. 
 
var a = {}; 
 
a.myFunction();

請記住這個Why is extending native objects a bad practice?

+0

如果你要擴展'Object.property'你應該最少用'Object.defineProperty()'做,並確保新屬性不可枚舉。 –