자바 스크립트에서 OO 프로그래밍을 배우고 있으며 클래스를 만드는 방법이 많이 있습니다. 나는 일반 구조로 읽은 것들을 많이 뽑아 냈지만 프로토 타이핑의 목적이 부 풀림을 피하기 위해 누락 된 것 같았습니다. 이 "클래스"의 프로토 타입 정의를 포함하면 객체가 줄어들지 않습니다 (즉, 객체 크기가 줄어들지 않음)? 이 전체 구조에 결함이 있습니까?자바 스크립트의 적절한 클래스 구성
감사합니다,
var Car = (function() {
//Private fields
var _make;
var _model;
//Constants (protected by encapsulation)
var NUM_OF_WHEELS = 4;
//Private methods
function getDesc() {
return _make + " " + _model;
}
//Public constructor
function thisCar(make, model, color) {
_make = make;
_model = model;
//public properties
thisCar.prototype.color = color;
}
//static properties
thisCar.carsInTheWorld = 50;
//static methods
thisCar.getNumberOfWheels = function() {
return NUM_OF_WHEELS * thisCar.carsInTheWorld;
};
//public properties
thisCar.prototype.color = "";
//public method
thisCar.prototype.startEngine = function() {
console.log(getDesc() + " engine started");
};
return thisCar;
})();
코멘트를 읽은 후 편집 여기에 제공된 링크는 내가 이해입니다.
개인 멤버에 대한 액세스가 필요한 클래스의 멤버는 프로토 타입에 추가 할 수 없으며 권한이 있어야합니다. 또한 프로토 타입을 생성자 함수에 포함하지 않는 것이 일반적입니다.
var Car = function (make, model, color) {//Public constructor
//Private fields
var _make = make;
var _model = model;
//Public fields
this.color = color;
//Private methods
function getDesc() {
return _make + " " + _model;
}
//Privileged functions (requiring private members)
this.startEngine = function() {
console.log(getDesc() + " engine started");
};
};
//public method
Car.prototype.sprayPaint = function (newColor) {
var oldColor = this.color;
this.color = newColor;
console.log("Your car has changed from " + oldColor + " to " + newColor);
};
//Public fields (if not declared in constuctor)
Car.prototype.fuel = 0;
//static properties
Car.carsInTheWorld = 0;
//static methods
Car.getNumberOfWheels = function() {
var NUM_OF_WHEELS = 4;
return NUM_OF_WHEELS * Car.carsInTheWorld;
};
모든 답변을 주셔서 감사합니다.
개인적으로 JS에서 이런 종류의 코딩은 나를 싫어하게 만듭니다. 엄청나게 역동적 인 언어이고, 당신 말이 맞습니다. 모든 것을 할 수있는 많은 방법이 있습니다. 필자는 결국 클래스 프레임 워크 (예 : JS.Class)를 사용하게 될 것이라고 절망적으로 생각합니다. –
코드에 많은 문제가 있습니다. 자세한 내용을 보려면 여기를 클릭하십시오. 당신은 내 JS JS * 올바른 * 상속에 대한 유형에 대한 게시물을 볼 수 있습니다 http://js-bits.blogspot.com/2010/08/javascript-inheritance-done-right.html –
코드를보고 솔직히, 당신은 [MDN] (https : //developer.mozilla.org/ko/JavaScript/Introduction_to_Object-Oriented_JavaScript) 객체 지향 자바 스크립트 – Starx