파란하늘의 지식창고
반응형
constructor는 객체를 만드는 기능함수를 반환하거나 설정을 하는 메소드이다.

아래와 같이 어떤 함수에 대해
function A() {
	document.writeln("a함수");
}

document.writeln(A.constructor);
호출한 결과는 아래와 같다.
function Function() { [native code] } 
constructor는 객체를 만드는 기능 함수를 반환하므로 object로 된 JavaScript의 모든 요소들이 다 가지고 있다.
예를 들어 아래와 같이 Object를 생성하게 되면
var a = new Object();
document.writeln(a.constructor);
호출한 결과는 아래와 같다.
function Object() { [native code] } 
사용자가 생성을 한 객체의 경우
function A() {
	this.name = "A함수";
	this.getName = function() {
		return this.name;
	}
}

a = new A();

document.writeln(a.constructor);
다음과 같다.
function A() { this.name = "A함수"; this.getName = function() { return this.name; } } 
즉. constructor는 이름 그대로 생성자 함수를 담고 있게 된다.
따라서 생성된 객체의 constructor 속성을 통해 해당 생성자 함수와 일치 여부 체크가 가능하다.
document.writeln(a.constructor == A);	//결과 : true
따라서 하나의 생성자로 여러개의 객체를 만든 경우 constructor가 동일하기 때문에 해당 객체들이 가지고 있는 내부 변수의 값이 다름과 별개로 생성자가 동일한지 체크가 가능하다.
function A() {
	this.name;
	this.setName = function(name) {
		this.name = name;
	}
	this.getName = function() {
		return this.name;
	}
}

a = new A();
a.setName("a함수");
b = new A();
b.setName("b함수");

document.writeln(a.getName());	//결과 "a함수"
document.writeln(b.getName());	//결과 "b함수"

document.writeln(a.constructor == b.constructor);	//결과 : true
위와 같이 두 객체가 각자 다른 값과 역할을 가지고 있어도 생성자 함수가 동일한지 여부의 체크가 가능하다.
반응형
profile

파란하늘의 지식창고

@Bluesky_

내용이 유익했다면 광고 배너를 클릭 해주세요