1. ตัวสร้าง
ค่าของตัวสร้างเป็นฟังก์ชั่น ในจาวาสคริปต์ค่าอาร์เรย์ฟังก์ชั่นและวัตถุประเภทยกเว้น null และ undefined มีแอตทริบิวต์ตัวสร้าง ชอบ:
คัดลอกรหัสดังนี้: var a = 12, // number
b = 'str', // string
c = false, // boolean
d = [1, 'd', function () {return 5;}], // array
e = {ชื่อ: 'e'}, // object
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. ต้นแบบ
Prototype เป็นคุณสมบัติของฟังก์ชั่น ชอบ:
คัดลอกรหัสดังต่อไปนี้: ฟังก์ชัน fn () {}
console.log (fn.prototype);
แอตทริบิวต์ต้นแบบส่วนใหญ่ใช้เพื่อใช้การสืบทอดใน JavaScript เช่น:
คัดลอกรหัสดังนี้: ฟังก์ชัน A (ชื่อ) {
this.name = ชื่อ;
-
A.prototype.show = function () {
console.log (this.name);
-
ฟังก์ชั่น b (ชื่อ) {
this.name = ชื่อ;
-
b.prototype = a.prototype;
test var = new b ('ทดสอบ');
test.show ();
มีปัญหาที่นี่
คัดลอกรหัสดังนี้: console.log (test.constructor);
นี่เป็นเพราะ b.prototype = a.prototype เปลี่ยนคอนสตรัคเตอร์ของ b.prototype เป็น a ดังนั้นคุณต้องกู้คืนตัวสร้างของ b.prototype:
คัดลอกรหัสดังนี้: ฟังก์ชัน A (ชื่อ) {
this.name = ชื่อ;
-
A.prototype.show = function () {
console.log (this.name);
-
ฟังก์ชั่น b (ชื่อ) {
this.name = ชื่อ;
-
b.prototype = a.prototype;
b.prototype.constructor = b;
VAR TEST = New B ('Test');
test.show ();
console.log (test.constructor);
เหตุผลในการทำเช่นนี้เป็นเพราะค่าของต้นแบบเป็นวัตถุและฟังก์ชั่นคอนสตรัคเตอร์เป็นฟังก์ชั่นที่มันอยู่นั่นคือ:
คัดลอกรหัสดังนี้: console.log (a.prototype.constructor === a);