2009-07-30 5 views
0

현재 AS3에서 JavaScript로 전환 중입니다.
나는 여전히 상속 개념을 이해하는데 약간의 문제가있다. 다음 코드가 제대로 작동되지 않는 이유
는 내가 이해하지 못하는 것은 :Javascript의 상속 - 프로토 타입 정의가 아닌 부분?

Base = function() { 
    this.coolVar = "great"; 
} 

SmallControl = function() { 

    // Inheritance: 
    this.prototype = new Base(); 
    this.prototype.constructor = SmallControl; 

    this.prototype.init = function(aMap) { 
     console.log('init'); 
     console.log('coolVar?: ' + this.coolVar); 
    } 
} 
var foo = new SmallControl(); 
//foo.init();   // --> TypeError: foo.init is not a function 
foo.prototype.init(); // --> works 

내가 α- 함수 모든 것이 잘 작동하는 "SmallControl"외부의 프로토 타입 정의를 넣으면 ...하지만 난 이해가 안 돼요 그.

// Create the super class 
Base = function() { 
    this.coolVar = "great"; 
}; 

// Create the new class 
SmallControl = function() { 
}; 
// Set the prototype of SmallControl to be an instance of Base. 
// This runs the Base constructor _immediately_ which sets up the variable 
SmallControl.prototype = new Base(); 
// Add the init method to the SmallControl class 
SmallControl.prototype.init = function(aMap) { 
    console.log('init'); 
    console.log('coolVar?: ' + this.coolVar); 
} 
// Create an instance of SmallControl  
var foo = new SmallControl(); 
foo.init(); 
+0

당신이 정의했을 때 this.prototype.init는 'this'가 SmallControl과 같지 않기 때문에 Prototype 객체가 아닌 Prototype 객체가 아닌 init 객체에 대해 init을 정의했다는 것을 알 수 있습니다. - "현재 객체"입니다. SmallControl의 런타임 인스턴스화. 그래서 foo.prototype.init가 작동합니다. "프로토 타입 정의를 바깥쪽에 넣으십시오 ..."라고 말하면 여러분은 다음과 같이 가정합니다 : SmallControl.prototype = function init (aMap) - 예, 그것은 정상적인 상속을 할 때 작동하고 숙어입니다. 예 : http://github.com/roblevintennis/Testing-and-Debugging-JavaScript/tree/master/code/objects/ – Rob

답변

1

난 당신이 뭔가를하려는 생각합니다. 객체의 실제 프로토 타입 (일부 환경에서는 __proto__ 속성으로 액세스 할 수 있지만 이식 가능하지 않음)은 객체가 생성 될 때 생성자의 prototype 속성으로 설정됩니다. 생성자의 프로토 타입 (프로토 타입에 속성 추가)에 대한 변경 사항은 실제 객체에 반영되지만 Constructor.prototype을 완전히 다른 객체로 설정하면 변경되지 않습니다.

생성자에서 생성 된 개체 (this)의 prototype 특성 을 설정하고 있습니다. 이 속성은 생성자 함수가 아닌 것에 특별한 의미가 없습니다. 함수 밖에서 설정하면 생성자 함수에서 설정합니다.

+0

- David - 멋진 고전적인 상속 예제! 로마,이게 효과가있을거야. 그러나 더 많은 효율성이 필요하다면 "Constructor Stealing"을 연구하려고 할 것입니다. 그런 다음 SmallControl.prototype = new Base();를 바꿀 것입니다. 왜냐하면 당신은 슈퍼 생성자를 두 번 호출 할 것이기 때문입니다. 그런 다음 inheritcProto (Sub, Sup)에 대한 도우미 메서드를 구현해야합니다. 이 코드는 모두 작동하고 TDD했습니다 : http://github.com/roblevintennis/Testing-and-Debugging-JavaScript – Rob

1

prototype 생성자의 의미있는 속성입니다 :