2014-09-22 4 views
0

JavaScript에서이 유형의 상속이 작동하지 않는 이유는 무엇입니까? 이 단계를 수행 할 수있는 방법이 있습니까? 내가 좋은 생각되지 않습니다 Function 프로토 타입을 확장 한JavaScript의 다중 상속

function base() {} 
base.prototype.findFirst = function() { 
    console.log("FindMe First"); 
} 

function base2() {} 
base2.prototype.findMe = function() { 
    console.log("FindMe "); 
} 

function inherit() { 
    base.call(this); 
    base2.call(this); 
} 

inherit.prototype = base.prototype; 
inherit.prototype.constructor = inherit; 
inherit.prototype = base2.prototype; 
inherit.prototype.constructor = inherit; 

var test = inherit(); 
test.findFirst(); 
test.findMe(); 
+1

자바 스크립트 개체에는 여러 프로토 타입 체인이있을 수 없습니다. 이것은 가능하지 않습니다. –

+3

#doingitwrong이라고 말씀 드리고 싶습니다. JS는 객체 지향 언어가 아닌 함수형 프로그래밍 언어입니다. OOP 구현이 원하는대로 작동하지 않기 때문에 OOP 구현을 시도하는 것보다 (예 : 클로저) 사용할 수있는 강력한 기능을 사용하는 것이 더 나을 것입니다. – Joe

+0

다중 상속은 가능한 경우 언어에서조차별로 좋은 아이디어가 아닙니다. 그리고 Javascript에서는 그렇지 않습니다. –

답변

0

도움이되지만 당신이 어떻게 작동하는지에 대한 아이디어를 제공하십시오. 다중 상속은 아니지만 상속 트리입니다.

Function.prototype.extend = function(child) 
{ 
    var childPrototype = child.prototype; 
    child.prototype = Object.create(this.prototype); 
    for (var property in childPrototype) { 
     if (childPrototype.hasOwnProperty(property)) { 
      child.prototype[property] = childPrototype[property]; 
     } 
    } 
    child.prototype.constructor = child; 
    return child; 
}; 

var base = (function() 
{ 
    var base = function() 
    { 

    }; 

    base.prototype.findFirst = function(x, y) 
    { 
     console.log("FindMe First"); 
    }; 

    return base; 

}()); 

var base2 = base.extend(function() 
{ 
    var base2 = function() 
    { 

    }; 

    base2.prototype.findMe = function(x, y) 
    { 
     console.log("FindMe "); 
    }; 

    return base2; 

}()); 

var inherit = base2.extend(function() 
{ 
    var inherit = function() 
    { 

    }; 

    return inherit; 

}()); 

var test = new inherit(); 
test.findFirst(); 
test.findMe(); 
+0

나는 당신이'childPrototype.hasOwnProperty (property)'테스트를 제거해야한다고 생각한다 - 그렇지 않으면 다중 레벨 상속이 잘 작동하지 않는다. – Bergi

+0

OP는 자신의 코드가하는 일을 모르는 것 같으므로 코드 대신 텍스트로 아이디어를 설명해 주시겠습니까? – Bergi

+0

@Bergi look [here] (http://brianflove.com/2013/09/05/javascripts-hasownproperty-method/)'hasOwnProperty()를 사용하면 루프가 개체의 상속 된 속성을 열거하는 것을 막을 수 있습니다. ' – bitWorking

1

base.prototype 및 base2.prototype으로 프로토 타입을 덮어 쓰고 있습니다. 따라서 base2.prtotype 즉 두 번째가 할당 된 유형을 저장합니다. 이제 상속 클래스 인 var test = new inherit();의 인스턴스를 생성하면 해당 테스트에 base2.property가 표시됩니다 (test.property.findMe();fimeMe() 메서드가 있음). 는 확장 또는 Mixin Multiple Inheritance

1

Mixins는 당신은 아마 순간에 다중 상속을 통해 해결하려는 같은 목표를 달성하기 위해 자바 스크립트에서 사용할 수있는 참조하도록해야 목표를 달성하기 위해.