Find conflicting method names in two JavaScript objects

I'm trying to simulate multiple inheritance in JavaScript, so I need to find a way to get a list of conflicting method names for two JavaScript objects. Is it possible to generate a list of function names for two objects and then find all function names that are the same between the two classes?

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"] 
+1
source share
2 answers

You need to do the following:

  • Get all the proper property names for each object.
  • Filter the functions.
  • Create a union of both sets.

The first two steps can be combined into one function:

 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; } 

Next, you need to find the union of many functions from two objects:

 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; } 

Now you can do whatever you want with these functions.

See the demo here: http://jsfiddle.net/gVCNd/

+2
source

If you just want to find generic named methods, then:

 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; } 

If you want only your own properties for objects, include your own property test:

 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; } 
0
source

Source: https://habr.com/ru/post/1311885/


All Articles