我正在尝试在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 :(得分:2)
您需要按照以下步骤操作:
前两个步骤可以合并为一个功能:
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/
答案 1 :(得分: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;
}