>  기사  >  웹 프론트엔드  >  JavaScript 클래스 및 상속 생성자 attribute_js 객체 지향

JavaScript 클래스 및 상속 생성자 attribute_js 객체 지향

WBOY
WBOY원래의
2016-05-16 18:33:14904검색

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); 🎜 >// 생성자로 obj 객체를 인스턴스화합니다.
var obj = new Foo();
console.log(obj.constructor === Foo); // true
// 위의 두 개를 바꿉니다. 단락 코드를 종합하면 다음과 같은 결론을 얻습니다.
console.log(obj.constructor.constructor === Function); // true


그러나 생성자가 프로토타입을 발견하면 흥미로운 점이 있습니다. 방금 일어난 일이에요.
각 함수에는 기본 속성 프로토타입이 있고 이 프로토타입의 생성자는 기본적으로 이 함수를 가리킨다는 것을 알고 있습니다. 다음 예시와 같습니다.


function Person (이름) {
this.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); >//는 위에 있을 것입니다. 두 줄의 코드를 결합하면 다음과 같은 결과가 나옵니다.
console.log(p.constructor.prototype.constructor === Person) // true


함수의 프로토타입을 재정의할 때(참고: 위 예제와의 차이점은 수정하는 것이 아니라 덮어쓰는 것임) 다음 예제와 같이 생성자 속성의 동작이 약간 이상합니다.



코드 복사
코드는 다음과 같습니다. 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 = }; >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"); .constructor === Person ); // true
console.log(Person.prototype.constructor === Person); // true
console.log(p.constructor.prototype.constructor === Person ); // 참

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.