簡體   English   中英

javascript為所有函數添加原型方法?

[英]javascript add prototype method to all functions?

有沒有辦法在不使用原型庫的情況下為所有javascript函數添加方法?

類似的東西:

Function.prototype.methodName = function(){ 


  return dowhateverto(this) 

 };

這是我到目前為止嘗試但它沒有工作。 也許這也是一個壞主意,如果可以,請告訴我為什么?

如果可以,我可以將它添加到我選擇的一組功能中

就像是 :

MyFunctions.prototype.methodName = function(){ 


  return dowhateverto(this) 

 };

其中MyFunctions是一個函數名數組

謝謝

當然。 函數是對象:

var foo = function() {};

Function.prototype.bar = function() {
  alert("bar");
};

foo.bar();

會警告“酒吧”

function one(){
    alert(1);
}
function two(){
    alert(2);
}

var myFunctionNames = ["one", "two"];

for(var i=0; i<myFunctionNames.length; i++) {
    // reference the window object, 
    // since the functions 'one' and 'two are in global scope
    Function.prototype[myFunctionNames[i]] = window[myFunctionNames[i]];
}


function foo(){}

foo.two(); // will alert 2

請嘗試使用Object.prototype:

Object.prototype.methodName = function(){ 

  return dowhateverto(this) 
};

但也注意到擴展原生物體的警告並不總是一個好主意。

在Javascript中無法真正可靠地操作Function.prototype; 它不是一個真正的對象,因為Function()構造函數需要返回一個函數,而不是一個對象。 但是,你也不能把它當成正常的功能。 當您嘗試訪問其“屬性”時,它的行為可能是未定義的,因瀏覽器而異。 另見這個問題

更改JS內置對象可以給你一些驚喜。
如果您添加外部庫或更改其中一個的版本,您永遠不會確定它們不會覆蓋您的擴展。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM