2015년 4월 27일 월요일

[JavaScript] 자바스크립트 생성자(Constructor) 함수와 객체

객체(Object)는 Object Literal Notation을 사용해서 생성할 수도 있을 뿐 아니라, Constructor 라는 함수를 이용해서도 생성이 가능하다. 이 Constructor 함수는 Object.constructor 프로퍼티를 이용해 접근이 가능하며, 우리가 일반적으로 new Object() 또는 Object Literal Notation을 이용해 생성한 객체들은 모두 자바스크립트 내장 함수인 Object() 라는 객체 생성자(Constructor)함수를 이용해 생성되는 것 이다.


var person1 = {
  firstName: "Jason",
  lastName: "Bourne",
  age: 25  
};

var person2 = new Object();

console.log(person1.constructor); //function Object() 
console.log(person2.constructor); //function Object() 
console.log(person1.constructor == person2.constructor); //true

이렇듯 person1 객체나 person2 객체 모두 같은 constructor에 의해 생성된다. 또 number, boolean string, array, regex 등도 각각의 constructor에 의해 생성된다.


var array = [];
var number = new Number(3);
var bool = new Boolean(true);
var str = new String("String");

console.log(array.constructor); //function Array()
console.log(number.constructor); //function Number()
console.log(bool.constructor); //function Boolean()
console.log(str.constructor); //function String()

즉 constructor(생성자)는 함수일 뿐이며, constructor 함수는 언제든지 생성될 수 있다는 뜻 이기도 하다.
예를들어, 위의 person 객체의 생성자 함수를 만든다 하면 아래와 같이 만들 수 있다.


function Person(firstName, lastName, age) {
  this.firstName = firstName;
  this.lastName = lastName;
  this.age = age;
  this.getInfo = function() {
    return "Name : " + firstName + " " + lastName + "\nAge : " + age;
  }
}

var person1 = new Person("Jason", "Bourne", 33);
var person2 = new Person("Jenny", "Laurence", 18);

console.log(person1.constructor); //function Person
console.log(person2.constructor); //function Person

new 키워드없이 생성자(Constructor)함수를 호출하게 되면 this 키워드때문에 윈도우 객체에 변수들이 추가되므로 주의하도록 하자(자세한건 this 키워드 관련 글을 참고하기).

2015년 4월 15일 수요일

[JavaScript] 자바스크립트 객체(Object)의 프로퍼티(Property)와 속성(Property Attribute)

예전에 적었던 자바스크립트 객체 소개글에서 말했던것 처럼, 객체란 여러가지 자료(Data)들과 함수(Function)들의 집합이다. 매우 간단하게 선언할 수 있고 접근될 수 있다. 이 글에서는 객체의 프로퍼티(Property)에 대해 이야기 해볼까 한다.

프로퍼티(Property)란 객체에 속한 데이터(Data)를 뜻한다. 아래의 코드에서는 name, age, occupationperson 객체의 프로퍼티가 되겠다.


var person = {
 name: "Jason",
 age: 25,
 occupation: "Student",
 getPersonProfile: function() {
  return "Name : " + this.name +
   "\nAge : " + this.age +
   "\nOccupation : " + this.occupation;
 }
};
person.newProperty = "newProperty";

console.log(person);
// { name: 'Jason',
//   age: 25,
//   occupation: 'Student',
//   getPersonProfile: [Function],
//   newProperty: 'newProperty' }

delete person.newProperty;

console.log(person);
// { name: 'Jason',
//   age: 25,
//   occupation: 'Student',
//   getPersonProfile: [Function] }

console.log(person.getPersonProfile());
// Name : Jason
// Age : 25
// Occupation : Student


위의 코드를 보면 person 객체 내부에 저 값들이 모두 저장된것 같지만, 사실 name, age, occupation 은 모두 값(Data)들이 저장된 메모리 위치를 가리킬 뿐이다. 그러므로, 프로퍼티에 저장된된 Data의 수정, 변경등은 모두 프로퍼티가 가리키는 메모리 위치에서 이루어 지는 일이다.

우리가 흔히 메소드(Method)라 부르는 항목은, 객체 내부에서 프로퍼티로 선언된 함수(Function)을 뜻하며, 위의 코드에서는 returnPersonProfile 프로퍼티가 바로 메소드 이다.

프로퍼티는 객체 선언시점에서와, 선언된 이후 시점 모두에서 추가가 가능하며, delete 키워드를 이용해서 삭제가 가능하다.

프로퍼티는 named data property, named accessor property 2가지 종류로 나뉘지며 named data propertynamed accessor property든, 프로퍼티들은 총 4가지의 속성(Attribute)으로 이루어지는데, 이러한 속성(Attribute)들은 특정 조건에서 프로퍼티의 행동양식(Behavior)을 저장하며, 또한 프로퍼티의 값(Value)를 저장한다.

Data Property와 Accessor Property는 2개의 같은 속성들(Configurable, Enumerable)과 2개의 다른 다른 속성들([Writable, Value], [Get, Set])로 구성된다

Named Data Property(데이터 프로퍼티)


저장된 Data 값에 관련된 프로퍼티이며 Value를 제외한 모든 속성(Attribute)들이 true||false, boolean 값으로 이루어져 있다. 위의 Person 객체에서는 name, age, occupation 프로퍼티들이 데이터 프로퍼티에 속한다
  • Configurable
    • 해당 프로퍼티가 delete 키워드 등으로 재정의(Redefine)될 수 있음을 가리킨다
    • 객체 프로퍼티 생성시 기본값으로 true 값을 가지며 false로 변경할 경우,  해당 프로퍼티 삭제되지 못하며, 이는 해당 프로퍼티의 속성(Attribute)에도 적용된다.
    • 객체 선언시 정의되지 않은 프로퍼티 같은경우에는 기본으로 false 값을 가진다.
  • Enumerable
    • 객체가 for-in 루프를 통과할시, 해당 프로퍼티가 for-in 루프에서 반환되어야(읽혀져야) 할지를 가리킨다.
    • 기본값으로는 true 값을 가진다.
    • 객체 선언시 정의되지 않은 프로퍼티 같은경우에는 기본으로 false 값을 가진다.
  • Writable
    • 프로퍼티의 Data 값이 수정될 수 있음을 가리킨다.
    • 기본값으로는 true 값을 가진다.
  • Value
    • 프로퍼티의 Data 값이다.
    • Value가 정해지지 않은경우에는 undefined값을 가진다.
    • 위의 Person 객체의 name 프로퍼티의 value 값은 "Jason"이다.

Named Accessor Property(접근 프로퍼티)


접근 속성은 프로퍼티의 데이터 값(Value)에 대한 접근에 관련된 속성이다. 데이터를 읽어(Retrieve)오는 Get 속성과 데이터를 저장하는 Set 속성을 가지며, 프로퍼티를 읽어오고 수정하는 기능을 한다. 위의 Person 객체에서는 getPersonProfile 메소드가 바로 Get의 역할을 한다 할 수 있다.

  • Configurable
    • 해당 프로퍼티가 delete 키워드 등으로 재정의(Redefine)될 수 있음을 가리킨다
    • 프로퍼티 생성시 기본값으로 true 값을 가지며 false로 변경할 경우,  해당 프로퍼티 삭제되지 못하며, 이는 해당 프로퍼티의 속성(Attribute)에도 적용된다.
    • 객체 선언시 정의되지 않은 프로퍼티 같은경우에는 기본으로 false 값을 가진다.
  • Enumerable
    • 객체가 for-in 루프를 통과할시, 해당 프로퍼티가 for-in 루프에서 반환되어야(읽혀져야) 할지를 가리킨다.
    • 기본값으로는 true 값을 가진다.
    • 객체 선언시 정의되지 않은 프로퍼티 같은경우에는 기본으로 false 값을 가진다.
  • Get
    • 프로퍼티가 읽어질 때, 호출되는 함수를 정한다. 이 속성을 통해 프로퍼티가 읽어져 반환되기 전에 어떠한 과정을 수행할지를 정할 수 있다.
    • Get 속성에 어싸인된 함수는 Parameter를 받을 수가 없다.
    • 기본값은 undefined.
  • Set
    • 프로퍼티가 수정될 때, 호출되는 함수를 정한다. 이 속성을 통해 프로퍼티가 수정되기 전에 어떠한 과정을 수행할지를 정할 수 있다.
    • Set 속성에 어싸인된 함수는 2개 이상의 Parameter를 받을 수가 없다.
    • 기본값은 undefined.

이러한 속성을 이용해서 아래와 같이 getPersonProfile 메소드를 대체할 수 있다.


var person = {
  name: "Jason",
  age: 25,
  occupation: "Student",
};

Object.defineProperty(person, "profile", {
  get: function() {
    return "Name : " + this.name +
      "\nAge : " + this.age +
      "\nOccupation : " + this.occupation;;
  }
});

console.log(person.profile);
// Name : Jason
// Age : 25
// Occupation : Student


프로퍼티(Property) 속성(Attribute) 정의하기


프로퍼티의 속성은
  • Object.defineProperty()
  • Object.defineProperties()
두가지 메소드를 이용해서 정의가 가능하다. 두 메소드의 차이는 단일 프로퍼티를 정의하는지(defineProperty), 여러가지 프로퍼티를 정의하는지(defineProperties)이다.

Object.defineProperty()

Object.defineProperty() 메소드는 프로퍼티를 소유한 객체, 프로퍼티의 이름, 프로퍼티 속성(Attribute) 정의객체(Descriptor Object), 이렇게 3개의 매개변수(Parameter)를 받는다.

사용법은 아래와 같다.


var person = {
  name: "Jason",
  age: 25,
  occupation: "Student",
  returnPersonProfile: function() {
    return "Name : " + this.name +
      "\nAge : " + this.age +
      "\nOccupation : " + this.occupation;
  }
};

//"name" 프로퍼티 속성을 정의한다
Object.defineProperty(person, "name", {
  configurable: true,
  enumerable: false,
  writable: false,
  value: "Laura"
});

console.log(person.name); //값이 Jason에서 Laura로 변경됬다

//프로퍼티 정의 객체 이기때문에 이렇게 객체를 선언해 사용할 수도 있다
var propertyDescriptor = {
  configurable: false,
  enumerable: false,
  writable: false,
  value: "New Property Value"
};

Object.defineProperty(person, "newProperty", propertyDescriptor);

//프로퍼티를 원하는 속성으로 생성할 수도 있다.
console.log(person.newProperty);

// configurable 을 false로 설정했기 때문에 아래 코드는 에러를 발생시킨다.
delete person.newProperty;
Object.defineProperty(person, "newProperty", {
  enumerable : true
});


Object.defineProperties()


defineProperties()가 여러개의 프로퍼티를 한꺼번에 정의한다. 매개변수로는 프로퍼티를 정의할 객체, 그리고 프로퍼티들의 속성 정의객체.

사용법은 아래와 같다.


var person = {
  name: "Jason",
  age: 25,
  occupation: "Student",
};

Object.defineProperties(person, {
  name: {
    configurable: false,
    enumerable: true,
    writable: false,
    value: "Laura"
  },

  profile: {
    get: function() {
      return "Name : " + this.name +
        "\nAge : " + this.age +
        "\nOccupation : " + this.occupation;;
    }
  }
});

console.log(person.profile);
// Name : Laura
// Age : 25
// Occupation : Student


프로퍼티 속성 읽어오기


프로터티의 속성은 Object.getOwnPropertyDescriptor() 메소드를 이용해 읽어올 수 있다. 매개변수로는 프로퍼티가 속한 객체와, 프로퍼티의 이름을 받는다.


var person = {
  name: "Jason",
  age: 25,
  occupation: "Student",
};

Object.defineProperty(person, "profile", {
  get: function() {
    return "Name : " + this.name +
      "\nAge : " + this.age +
      "\nOccupation : " + this.occupation;;
  }
});

var propertyDescriptor_name = Object.getOwnPropertyDescriptor(person, "name");

console.log(propertyDescriptor_name);
// { value: 'Jason',
//   writable: true,
//   enumerable: true,
//   configurable: true }

var propertyDescriptor_age = Object.getOwnPropertyDescriptor(person, "age");
console.log(propertyDescriptor_age);
// { value: 25,
//   writable: true,
//   enumerable: true,
//   configurable: true }


var propertyDescriptor_occupation = Object.getOwnPropertyDescriptor(person, "occupation");
console.log(propertyDescriptor_occupation);
// { value: 'Student',
//   writable: true,
//   enumerable: true,
//   configurable: true }

var propertyDescriptor_Profile = Object.getOwnPropertyDescriptor(person, "profile");
console.log(propertyDescriptor_Profile);
// { get: [Function],
//   set: undefined,
//   enumerable: false,
//   configurable: false }
// 객체 선언시 내부에서 정의된 프로퍼티가 아니기 때문에 configurable 과 enumerable 값이 모두 false 이다.

2015년 4월 2일 목요일

[JavaScript] 자바스크립트 this 키워드의 모든것

this 키워드를 이해하기 위해서는 Execution Context를 이해해야하니, 혹시 Execution Context를 모른다면 이 글(클릭하기)을 읽어 봐 주길 바란다.

자바스크립트에서는 매번 함수의 호출마다 새로운 Execution Context가 생성된다. 이 Execution Context는 Lexical Environment, Variable Environment, 그리고 ThisBinding에 대한 정보를 가지고 있는데, 바로 this 키워드가 이 이 thisbinding이라고 할 수 있겠다. this값은 해당 함수가 현재 어느 Execution Context에서 구동하고 있는지를 알려준다.

Context는 함수 호출에 의해 새로이 생성되며, thisBinding 값은 함수 호출시점에 정해지게 된다. 정확히 말하자면 ECMAScript 내부에서 Function call 발생할 때, 함수의 Arguments List와 thisArg라 불리는 두 객체를 전달하게 되는데, ECMAScript® Language Specification 10.4.3에 따르면 여기서 아래의 과정을 거친후 thisBinding의 값이 결정 된다.
  1. 만약 함수가 strict mode에서 정의된 함수인지를 확인한 후, thisBinding 값은 전달된 thisArg값이 된다.
  2. (strict mode에서 정의된 함수가 아니고) thisArg 값이 null 이나 undefined라면면,  thisBinding 값은 global object가 된다.
  3. 전달된 Type(thisArg) 연산으로 얻어진 thisArg 값의 Typeobject(객체)가 아니라면, thisBinding 값은 toObject(thisArg) 오퍼레이션을 통해 객체화된 객체가 된다.
    • Type() 함수는 ECMA스크립트 내부 함수로, 주어진 변수의 Type을 연산합니다.
    • toObjecT() 함수는 주어진 변수를 Boolean, Number, String, Object 형으로 변환 합니다
  4. 위 모든 과정에서 thisBinding 값이 정해지지 않았다면, 전달된 thisArgthisBinding이 된다.

참고로 funciton.prototype.call, function.prototype.apply 와 같은 this 값을 수정 가능케 하는 기능들은 모두 thisArg 값을 사용자가 전달할 수 있게 함으로써 가능한 기능들이다.

그렇다면, 일반적으로는 이 thisArg 값이 어떻게 결정 되는 것 일까? 이는 함수 호출(Function Call) 과정을 설명한 ECMAScript® Language Specification 11.2.3 에 잘 정의 되어 있다 - 6번과 7번에 주목하자.

*우선 이전에 몇가지 알아야 될것들이 있다

  • 함수가 저장된 주소인 reference 값은 base value, referenced name, strict reference flag, 이 3가지 요소로 이루어져 있다
    • referenced namestring 값으로 저장된 function identifier이다
    • strict reference flagboolean 값으로, strict mode 에서 실행되는 코드인지를 표시한다
    • base valuereference가 속한 context object를 가리킨다

thisArg값은 함수 호출(Function Call)의 6번째 과정에서에서 결정되며, 함수 호출의 전체 과정은 아래와 같다.

  1. 함수 객체의 이름(MemberExpression)을 해석해서 함수가 저장된 레퍼런스 값인 ref를 얻는다.
  2. GetValue(ref) 오퍼레이션을 이용, 함수 func을 불러온다.
  3. 주어진 arguments 들로 argList를 생성한다.
  4. Type(func) 오퍼레이션을 이용, 함수 func의 타입을 확인한후, 객체타입이 아니라면 TypeError Exception 을 발생시킨다.
  5. IsCallable(func) 오퍼레이션을이용, 함수 func의 호출이 가능한지를 확인한 후, 불가능하다면 TypeError Exception을 발생시킨다.
  6. Type(ref)를 이용, ref의 타입을 확인한 후, reference 타입이라면
    1. IsPropertyReference(ref) 오퍼레이션을 이용, ref가 object 또는 primitive wrapper object(String, Boolean, Number 등의 객체)에 속한 property 라면 thisArg값은 getBase(ref) 오퍼레이션에서 얻어진 해당 객체 인스턴스가 된다.
    2. 그 이외의 경우에는 ref가 속한 Environment Record(Variable Environment Object)라면 getBase(ref)에서 얻어진 값의 ImplicitThisValue()가 바로 thisArg가 된다.
  7. 만약 Type(ref)를 이용해 확인한 ref의 타입이 reference 가 아니라면, thisArg값은 undefined가 된다.
  8. Call 오퍼레이션을 이용, thisArg 값과 argList를 전달해 함수를 호출한 후 그 결과값을 리턴한다.

결국 각각의 경우에 따라 thisBinding의 값이 달라지니 좀 헷깔린다. 그래서 자주 보게되는 상황들을 Case By Case 로 설명을 해보려 한다.

* 참고로 this 키워드는 객체이기 대문에 '.'(Dot Notation) 또는 '[', ']'(Bracket Notation) 를 이용해서도 this 객체의 변수나 함수를 호출 할 수 있다.
* 위 과정을 읽었으면 알겠지만 strict 모드에서는 함수 호출시 thisArg값은 non-strict mode 일때와는 다르다.


1. Declaration environment record에 존재하는 함수 호출(Function Call)


  • 위의 6-2번 과정이다. ImplicitThisValue() 는 모든 declaration에 대해 undefined를 리턴한다
  • 이 때문에 this 키워드는 strict mode에서는 undefined 값을, non-strict mode에서는 global object(window object)값을 참조하게 된다.


function invokeFunction() {
    console.log("invokeFunction");
    console.log(this);//Window
    demo1();
    function demo1() {
 console.log("demo1");
 console.log(this);//Window

 var demo2 = function() {
     console.log("demo2");
     console.log(this);//Window

     var demo3 = function() {
  console.log("demo3");
  console.log(this);//Window
     };
     demo3();
 };
 demo2();
    }
}
console.log(this);//Window
invokeFunction();


2. new 키워드를 이용해 객체(object)로 인스턴스화 될 때, this 값은 언제나 인스턴스화된 객체를 참조한다.

  • 위 과정의 6-1번에 속하는 경우이다. 호출된 함수가 객체의 property인 경우이다


function thisObject(name, property) {
    this.name = name;
    this.property = property

    this.thisValue = this;

    this.f = function() {
 console.log("this in function f \n" + this); //object
    }
}

var demo = new thisObject("testObject", 0);
console.log("demo.thisvalue is " + demo.thisValue); //object demo


3. 객체의 메소드로써 호출될 때, this 값은 언제나 인스턴스화된 객체를 참조한다.


  • 메소드란 객체의 프로퍼티(property)로 존재하는 함수를 한다.
  • 이 경우 또한 위 과정의 6-1번의 경우가 되겠다.


var a = {
    test : function() {
 return this;
    }
};

a.test();// object 'a'

var b = {};
b.test = a.test;

b.test()// object 'b'


4. function.prototype.call 또는 function.prototype.apply 메소드를 이용해 호출될 때


  • thisArg의 값은 사용자에 의해 주어진다.


function test() {
    return this;
}
test();// windows

var a = {};
test.apply(a);// object 'a'

test.call(a);// object 'a'