생성자 함수를 사용하여 사용자 정의 개체 만들기

JScript의 강력한 기능은 생성자 함수를 정의하여 스크립트에 사용할 사용자 지정 프로토타입 기반 개체를 만드는 것입니다. 프로토타입 기반 개체의 인스턴스를 만들려면 우선 생성자 함수를 정의해야 합니다. 이 프로세스에서는 새로운 개체를 만들고 초기화합니다. 즉 속성을 만들고 초기 값을 할당합니다. 이 프로세스가 완료되면 생성자는 생성한 개체에 대한 참조를 반환합니다. 생성자 내부에서는 this 문을 사용하여 생성된 개체가 참조됩니다.

생성자에 속성 추가

다음 예제에서는 pasta 개체를 위한 생성자 함수를 정의합니다. this 문을 사용하면 생성자가 개체를 초기화할 수 있습니다.

// pasta is a constructor that takes four parameters.
function pasta(grain, width, shape, hasEgg) {
   this.grain = grain;    // What grain is it made of?
   this.width = width;    // How many centimeters wide is it?
   this.shape = shape;    // What is the cross-section?
   this.hasEgg = hasEgg;  // Does it have egg yolk as a binder?
}

개체 생성자를 정의한 후 new 연산자를 사용하여 개체의 인스턴스를 만듭니다. 여기서 pasta 생성자를 사용하여 spaghetti 개체와 linguine 개체를 만듭니다.

var spaghetti = new pasta("wheat", 0.2, "circle", true);
var linguine = new pasta("wheat", 0.3, "oval", true);

개체 인스턴스에 속성을 동적으로 추가할 수 있지만 변경 내용은 그 한 인스턴스에만 영향을 줍니다.

// Additional properties for spaghetti. The properties are not added
// to any other pasta objects.
spaghetti.color = "pale straw";
spaghetti.drycook = 7;
spaghetti.freshcook = 0.5;

생성자 함수를 수정하지 않고 개체의 모든 인스턴스에 속성을 추가하려는 경우에는 생성자의 프로토타입 개체에 속성을 추가할 수 있습니다. 자세한 내용은 고급 개체 만들기(Visual Studio - JScript)를 참조하십시오.

// Additional property for all pasta objects. 
pasta.prototype.foodgroup = "carbohydrates";

생성자에 메서드 추가

개체 정의에 메서드(함수)를 포함시키는 방법 중 하나는 다른 곳에 정의된 함수를 참조하는 생성자 함수에 속성을 포함시키는 것입니다. 이러한 함수들은 생성자 함수와 마찬가지로 this 문을 사용하여 현재 개체를 참조합니다.

다음 예제에서는 함수가 개체 값을 표시할 경우 호출될 toString 메서드를 포함하도록 앞에서 정의한 pasta 생성자 함수를 확장합니다. 일반적으로, JScript에서는 문자열이 필요한 상황에서 개체가 사용될 때 개체의 toString 메서드를 사용합니다. toString 메서드를 명시적으로 호출할 필요가 있는 경우는 거의 없습니다.

// pasta is a constructor that takes four parameters.
// The properties are the same as above.
function pasta(grain, width, shape, hasEgg) {
   this.grain = grain;    // What grain is it made of?
   this.width = width;    // How many centimeters wide is it?
   this.shape = shape;    // What is the cross-section?
   this.hasEgg = hasEgg;  // Does it have egg yolk as a binder?
   // Add the toString method (defined below).
   // Note that the function name is not followed with parentheses;
   // this is a reference to the function itself, not a function call.
   this.toString = pastaToString;
}

// The function to display the contents of a pasta object.
function pastaToString() {
   return "Grain: " + this.grain + "\n" +
          "Width: " + this.width + " cm\n" +
          "Shape: " + this.shape + "\n" +
          "Egg?:  " + Boolean(this.hasEgg);
}

var spaghetti = new pasta("wheat", 0.2, "circle", true);
// Call the method explicitly.
print(spaghetti.toString());
// The print statement takes a string as input, so it
//  uses the toString() method to display the properties
// of the spaghetti object.
print(spaghetti);

다음과 같이 출력됩니다.

Grain: wheat
Width: 0.2 cm
Shape: circle
Egg?:  true
Grain: wheat
Width: 0.2 cm
Shape: circle
Egg?:  true

참고 항목

기타 리소스

프로토타입 기반 개체

JScript 개체