2013-03-11 32 views
1

我想模擬JavaScript中的多重繼承,所以我需要找到一種方法來獲取兩個JavaScript對象的衝突方法名列表。是否有可能爲兩個對象生成函數名稱列表,然後找到兩個類之間相同的所有函數名稱?在兩個JavaScript對象中查找衝突的方法名

function base1(){ 
     this.printStuff = function(){ 
      return "Implemented by base1"; 
     }; 
    } 

    function base2(){ 
     this.printStuff = function(){ 
      return "Implemented by base2"; 
     }; 
    } 

function getConflictingFunctionNames(object1, object2){ 
    //get a list of conflicting function names between the two objects. 

    //to be implemented. 
} 

console.log(getConflictingFunctionNames(base1, base2)); //this should print ["printStuff"] 
+0

爲什麼會打印'「object1」,「object2」'? – 2013-03-11 01:50:06

+0

我想我需要獲得每個對象中所有方法的列表,如此處所述,然後找到所有在它們中都相同的方法名稱。 http://stackoverflow.com/questions/2257993/how-to-display-all-methods-in-a-javascript-object – 2013-03-11 01:50:22

+0

@ExplosionPills我修正了這個錯誤。我打算寫'printstuff''。 – 2013-03-11 01:51:12

回答

2

你需要遵循以下步驟:

  1. 獲取所有每個對象的自身屬性名稱。
  2. 過濾功能。
  3. 創建兩個集合的並集。

前兩個步驟可以合併成一個單一的功能:

function getOwnFunctionNames(object) { 
    var properties = Object.getOwnPropertyNames(object); 
    var length = properties.length; 
    var functions = []; 

    for (var i = 0; i < length; i++) { 
     var property = properties[i]; 
     if (typeof object[property] === "function") 
      functions.push(property); 
    } 

    return functions; 
} 

接下來你需要找到一組的兩個對象的功能的結合:

function getConflictingFunctionNames(object1, object2) { 
    var functions1 = getOwnFunctionNames(object1); 
    var functions2 = getOwnFunctionNames(object2); 
    var length = functions1.length; 
    var functions = []; 

    for (var i = 0; i < length; i++) { 
     var functionName = functions1[i]; 
     if (functions2.indexOf(functionName) >= 0) 
      functions.push(functionName); 
    } 

    return functions; 
} 

現在你可以用這些功能做任何你想做的事情。

在這裏看到演示:http://jsfiddle.net/gVCNd/

0

如果你只是想找到共同的命名方法,那麼:

function getCommonNamedMethods(obj1, obj2) { 
    var result = []; 

    for (var p in obj1) { 

    if (typeof obj1[p] == 'function' && typeof obj2[p] == 'function') { 
     result.push(p); 
    } 
    } 
    return result; 
} 

如果你想的對象只有自己的屬性,包括自己的屬性測試:

function getCommonNamedMethods(obj1, obj2) { 
    var result = []; 

    for (var p in obj1) { 

    if (obj1.hasOwnProperty(p) && typeof obj1[p] == 'function' && 
     obj2.hasOwnProperty(p) && typeof obj2[p] == 'function') { 
     result.push(p); 
    } 
    } 
    return result; 
}