1. 생성자
생성자의 값은 함수입니다. JavaScript에서는 NULL 및 UNDEFIND를 제외한 유형의 값, 배열, 함수 및 객체에는 생성자 속성의 값 이이 값, 배열, 기능 또는 객체 생성자입니다. 좋다:
다음과 같이 코드를 복사하십시오 : var a = 12, // 숫자
b = 'str', // string
c = 거짓, // 부울
d = [1, 'd', function () {return 5}], // 배열
e = {이름 : 'e'}, // 객체
f = function () {return 'function';
Console.log ( 'a :', a.constructor);
Console.log ( 'b :', b.constructor);
Console.log ( 'C :', C.Constructor);
console.log ( 'd :', d.constructor);
console.log ( 'e :', e.constructor);
console.log ( 'f :', f.constructor);
위의 생성자는 JavaScript로 내장되어 있으며 다음과 같은 생성자를 사용자 정의 할 수도 있습니다.
코드 사본은 다음과 같습니다.
함수 A (이름) {
this.name = 이름;
}
var a = new a ( 'a');
Console.log (a.constructor);
생성자를 호출 할 때는 새 키워드를 사용해야합니다.
코드 사본은 다음과 같습니다. var a = 4;
var b = 새 숫자 (4);
Console.log ( 'a :', typeof a);
Console.log ( 'b :', typeof b);
2. 프로토 타입
프로토 타입은 함수의 속성으로, 기능의 프로토 타입 속성 값은 함수와 동일한 이름이며 익명 함수의 프로토 타입 속성을 개체라고합니다. 좋다:
다음과 같이 코드를 복사하십시오 : function fn () {}
Console.log (fn.prototype);
프로토 타입 속성은 주로 다음과 같은 JavaScript의 상속을 구현하는 데 사용됩니다.
다음과 같이 코드를 복사하십시오 : 함수 a (이름) {
this.name = 이름;
}
A.prototype.show = function () {
Console.log (this.name);
};
함수 B (이름) {
this.name = 이름;
}
B. 프로토 타입 = A. 프로로 타입;
var test = new b ( 'test');
test.show (); // 테스트
여기에는 문제가 있습니다. 테스트의 생성자는 실제로 기능 B가 아닌 기능입니다.
다음과 같이 코드를 복사하십시오. console.log (test.constructor);
이것은 B. prototype = A. prototype이 B. prototype의 생성자를 A로 변경했기 때문에 B. prototype의 생성자를 복원해야하기 때문입니다.
다음과 같이 코드를 복사하십시오. 함수 a (name) {
this.name = 이름;
}
A.prototype.show = function () {
Console.log (this.name);
};
함수 B (이름) {
this.name = 이름;
}
B. 프로토 타입 = A. 프로로 타입;
B. prototype.constructor = b;
var test = new b ( 'test');
test.show (); // 테스트
Console.log (Test.constructor);
이를 수행하는 이유는 프로토 타입의 값이 객체이고 생성자 함수가 위치한 기능, 즉 다음과 같은 기능이기 때문입니다.
다음과 같이 코드를 복사하십시오