The Constructor Pattern

고전적인 객체 지향 프로그래밍 언어에서 생성자는 일단 메모리가 할당되면 새로 생성 된 객체를 초기화하는 데 사용되는 특별한 방법입니다. JavaScript에서는 거의 모든 것이 객체이기 때문에 우리는 객체 생성자에 대해 관심을 가져야 합니다.

객체 생성자는 특정 유형의 객체를 만드는 데 사용됩니다. 생성자는 사용하기 위한 객체를 준비하고 객체가 처음 생성될 때 전달받은 인자를 사용하여 멤버 속성과 메소드를 초기화 할 수 있습니다.

Object Creation

JavaScript에서 새로운 객체를 만드는 세 가지 일반적인 방법은 다음과 같습니다.

// Each of the following options will create a new empty object:

var newObject = {};

// or
var newObject = Object.create( Object.prototype );

// or
var newObject = new Object();

마지막 예제의 "Object" 생성자가 특정 값에 대한 래퍼 객체를 만들거나 값이 전달되지 않은 경우 빈 객체를 만들어 반환합니다.

다음은 키와 값을 객체에 할당 할 수있는 네 가지 방법이 있습니다.

// ECMAScript 3 compatible approaches

// 1. Dot syntax

// Set properties
newObject.someKey = "Hello World";

// Get properties
var value = newObject.someKey;



// 2. Square bracket syntax

// Set properties
newObject["someKey"] = "Hello World";

// Get properties
var value = newObject["someKey"];



// ECMAScript 5 only compatible approaches
// For more information see: http://kangax.github.com/es5-compat-table/

// 3. Object.defineProperty

// Set properties
Object.defineProperty( newObject, "someKey", {
    value: "for more control of the property's behavior",
    writable: true,
    enumerable: true,
    configurable: true
});

// If the above feels a little difficult to read, a short-hand could
// be written as follows:

var defineProp = function ( obj, key, value ){
  var config = {
    value: value,
    writable: true,
    enumerable: true,
    configurable: true
  };
  Object.defineProperty( obj, key, config );
};

// To use, we then create a new empty "person" object
var person = Object.create( Object.prototype );

// Populate the object with properties
defineProp( person, "car", "Delorean" );
defineProp( person, "dateOfBirth", "1981" );
defineProp( person, "hasBeard", false );

console.log(person);
// Outputs: Object {car: "Delorean", dateOfBirth: "1981", hasBeard: false}


// 4. Object.defineProperties

// Set properties
Object.defineProperties( newObject, {

  "someKey": {
    value: "Hello World",
    writable: true
  },

  "anotherKey": {
    value: "Foo bar",
    writable: false
  }

});

// Getting properties for 3. and 4. can be done using any of the
// options in 1. and 2.

이 책의 뒷 부분에서 보게 되겠지만, 다음과 같이 상속에 사용할 수 도 있습니다.

// Usage:

// Create a race car driver that inherits from the person object
var driver = Object.create( person );

// Set some properties for the driver
defineProp(driver, "topSpeed", "100mph");

// Get an inherited property (1981)
console.log( driver.dateOfBirth );

// Get the property we set (100mph)
console.log( driver.topSpeed );

Basic Constructors

앞에서 보았 듯이 JavaScript는 클래스 개념을 지원하지 않지만 객체를 만들 수 있는 특별한 생성자 함수를 지원합니다. 생성자 함수에 "new" 키워드를 접두사로 붙이면 JavaScript가 함수를 생성자처럼 동작시키고 해당 함수로 정의 된 멤버로 새 객체를 인스턴스화 합니다.

생성자 내에서 this는 생성되는 새 객체를 참조하는 키워드입니다. 객체 생성을 다시 한 번 살펴보면 기본 생성자는 다음과 같이 보일 수 있습니다.

function Car( model, year, miles ) {

  this.model = model;
  this.year = year;
  this.miles = miles;

  this.toString = function () {
    return this.model + " has done " + this.miles + " miles";
  };
}

// Usage:

// We can create new instances of the car
var civic = new Car( "Honda Civic", 2009, 20000 );
var mondeo = new Car( "Ford Mondeo", 2010, 5000 );

// and then open our browser console to view the
// output of the toString() method being called on
// these objects
console.log( civic.toString() );
console.log( mondeo.toString() );

위의 것은 생성자 패턴의 간단한 버전이지만 몇 가지 문제가 있습니다. 하나는 상속을 어렵게 만들고 다른 하나는 toString()과 같은 함수가 Car 생성자를 사용하여 만든 새 객체 각각에 대해 재정의된다는 것입니다. 이 기능은 Car 유형의 모든 인스턴스간에 이상적으로 공유되어야 하므로 매우 부적합 합니다.

고맙게도 객체를 구성하는 데 ES3 및 ES5와 호환되는 여러 가지 옵션이 있으므로이 제한 사항을 해결하는 것은 간단합니다.

Constructors With Prototypes

함수는 JavaScript의 거의 모든 객체와 마찬가지로 "프로토 타입"객체를 포함합니다. JavaScript 생성자를 호출하여 객체를 만들면 생성자의 프로토 타입의 모든 속성을 새 객체에서 사용할 수 있습니다. 이 방식으로 동일한 프로토 타입에 액세스하는 여러 Car 객체를 만들 수 있습니다. 따라서 다음과 같이 원래 예제를 확장 할 수 있습니다.

function Car( model, year, miles ) {

  this.model = model;
  this.year = year;
  this.miles = miles;

}


// Note here that we are using Object.prototype.newMethod rather than
// Object.prototype so as to avoid redefining the prototype object
Car.prototype.toString = function () {
  return this.model + " has done " + this.miles + " miles";
};

// Usage:

var civic = new Car( "Honda Civic", 2009, 20000 );
var mondeo = new Car( "Ford Mondeo", 2010, 5000 );

console.log( civic.toString() );
console.log( mondeo.toString() );

results matching ""

    No results matching ""