javascript - 객체 생성과 함수
자꾸 까먹어서 다시 정리하는 javascript 관련 정리 싸지르기 1.
1. 객체 생성
1.1 {}
built in object인 Object를 생성한다.
javascript의 Object는 Dictionary라서 key:value 쌍으로 property를 지정한다.
var o = {}
o.a = 1
1.2 new 연산자
new 연산자를 사용하여 객체를 생성할 수 있다.
function A(_a){
this.a = _a;
}
var o = new A(1);
new 뒤의 함수는 java의 생성자 함수처럼 property를 초기화할 수 있다.
new는 연산자로서, 아래와 같은 작업을 한다.
a. 비어있는 객체 생성
b. 생성된 객체를 this로 하여, new 뒤의 함수 실행
다음과 같이 표현할 수 있다.
var new_op = function(_v){
var anonym = {} // ------------- (a)
A.call( anonym, _v ); // ------------- (b) anonym을 this로 A실행
return anonym;
}
cf) 1. Object.create(...)을 사용하여 객체를 생성할 수도 있으나 다른 주제로 정리함.
2. call(), apply() 에 대하여 다른 주제로 정리함.
2. 객체와 함수 - property
function A(_a){
this.a = _a;
}
var o = new A(1);
console.log(A); // ----------- (a) 함수 A
console.log(o); // ------------ (b) 함수 A의 객체 o
firefox console을 보면, (a), (b)의 결과는 각각 아래와 같다.
(a) Function A (b) object o
A.prototype.constructor == o.__proto__.constructor ?!
(a) Function A의 로그
함수 A의 property로 arguments, caller 와 함께 prototype이 존재한다.
javascript engine은 소스상의 함수들에 대하여 다음과 같은 작업을 수행한다.
A.prototype = {constructor:A}
(b) object o의 로그
A에 정의된 property a외에, __proto__가 존재한다. 아래 log의 결과를 보자.
console.log(A.prototype == o.__proto__); // (1) true
console.log(o.__proto__.constructor) // (2) A
console.log(o.constructor) // (3) A
console.log(o.prototype) // (4) undefined
console.log(A.prototype.constructor) // (5) A
console.log(A.constructor) // (6) Function
console.log(A.__proto__.constructor) // (7) Function
(1) A.prototype에 할당된 객체와 o.__proto__에 할당된 객체는 값이 같다.
(2), (3) __proto__ 없이 접근할 수 있다!!! __proto__는 객체가 자신의 생성자 함수의 prototype property를 참조할 수 있도록 하는 특수 property이다. (__proto__는 firefox, chrome에서 사용하는 이름이다.)
(4) 객체에는 prototype property가 없다.
(5) A.prototype = {constructor:A} 이므로.
(6), (7) 은 나중에 정리. 참고만 하자.
결론
1. 함수가 생성될 때 A.prototype = {constructor:A} 실행.
2. 객체가 생성되면 함수의 prototype 영역에 대한 참조 property 발생.( __proto__ )