javascript 생 성자 속성
3772 단어 JavaScriptprototype
본 고 는 자 바스 크 립 트 의 constructor 속성 을 소개 합 니 다.이 속성 은 자 바스 크 립 트 클래스 와 계승 을 이해 하 는 중요 한 기초 입 니 다.
constructor 속성 은 현재 대상 을 만 드 는 구조 함 수 를 항상 가리 키 고 있 습 니 다.예 를 들 어 다음 예:
// var foo = new Array(1, 56, 34, 12);
var arr = [1, 56, 34, 12];
console.log(arr.constructor === Array); // true
// var foo = new Function();
var Foo = function() { };
console.log(Foo.constructor === Function); // true
// obj
var obj = new Foo();
console.log(obj.constructor === Foo); // true
// ,
console.log(obj.constructor.constructor === Function); // true
하지만 constructor 가 prototype 을 만 났 을 때 재 미 있 는 일이 벌 어 졌 다.
우 리 는 모든 함수 에 기본 속성 인 prototype 이 있다 는 것 을 알 고 있 습 니 다. 이 prototype 의 constructor 는 기본적으로 이 함 수 를 가리 키 고 있 습 니 다.다음 과 같은 예 에서 보 듯 이:
function Person(name) {
this.name = name;
};
Person.prototype.getName = function() {
return this.name;
};
var p = new Person("ZhangSan");
console.log(p.constructor === Person); // true
console.log(Person.prototype.constructor === Person); // true
//
console.log(p.constructor.prototype.constructor === Person); // true
그리고 우리 가 함수 의 prototype 을 다시 정의 할 때 (주의: 상례 와 의 차이, 여 기 는 수정 이 아니 라 덮어 쓰기) constructor 속성의 행 위 는 좀 이상 합 니 다. 다음 과 같은 예 입 니 다.
function Person(name) {
this.name = name;
};
Person.prototype = {
getName: function() {
return this.name;
}
};
var p = new Person("ZhangSan");
console.log(p.constructor === Person); // false
console.log(Person.prototype.constructor === Person); // false
console.log(p.constructor.prototype.constructor === Person); // false
왜 일 까요?
Person. prototype 을 덮어 쓸 때 다음 과 같은 코드 작업 을 하 는 것 과 같 기 때 문 입 니 다.
Person.prototype = new Object({
getName: function() {
return this.name;
}
});
그리고 constructor 속성 은 항상 자신의 구조 함 수 를 만 드 는 것 을 가리 키 기 때문에 이때 Person. prototype. constructor = = Object, 즉:
function Person(name) {
this.name = name;
};
Person.prototype = {
getName: function() {
return this.name;
}
};
var p = new Person("ZhangSan");
console.log(p.constructor === Object); // true
console.log(Person.prototype.constructor === Object); // true
console.log(p.constructor.prototype.constructor === Object); // true
어떻게 이런 문 제 를 수정 합 니까?방법 도 간단 합 니 다. Person. prototype. constructor 를 다시 덮어 쓰 면 됩 니 다.
function Person(name) {
this.name = name;
};
Person.prototype = new Object({
getName: function() {
return this.name;
}
});
Person.prototype.constructor = Person;
var p = new Person("ZhangSan");
console.log(p.constructor === Person); // true
console.log(Person.prototype.constructor === Person); // true
console.log(p.constructor.prototype.constructor === Person); // true