1. Konstruktor
Nilai konstruktor adalah fungsi. Dalam JavaScript, Nilai, Array, Fungsi dan Objek Jenis Kecuali Null dan Tidak Ditentukan memiliki atribut konstruktor. menyukai:
Salin kode sebagai berikut: var a = 12, // nomor
b = 'str', // string
c = false, // boolean
d = [1, 'D', function () {return 5;}], // array
e = {name: 'e'}, // objek
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);
Konstruktor di atas adalah bawaan dalam JavaScript, dan kami juga dapat menyesuaikan konstruktor, seperti:
Salinan kode adalah sebagai berikut:
fungsi a (name) {
this.name = name;
}
var a = baru a ('a');
Console.log (a.constructor);
Saat memanggil konstruktor, Anda perlu menggunakan kata kunci baru.
Salinan kode adalah sebagai berikut: var a = 4;
var b = angka baru (4);
console.log ('A:', typeof a); // a: nomor
Console.log ('B:', TypeOf B); // B: Objek
2. Prototipe
Prototipe adalah properti dari suatu fungsi. menyukai:
Salin kode sebagai berikut: function fn () {}
console.log (fn.prototype); // fn {}
Atribut prototipe terutama digunakan untuk mengimplementasikan warisan dalam JavaScript, seperti:
Salin kode sebagai berikut: Fungsi a (name) {
this.name = name;
}
A.prototype.show = function () {
console.log (this.name);
};
fungsi b (name) {
this.name = name;
}
B.Prototype = a.prototype;
var test = baru b ('test');
test.show ();
Ada masalah di sini.
Salin kode sebagai berikut: Console.log (test.constructor);
Ini karena B.Prototype = A.Prototype mengubah konstruktor B.Prototipe ke A, jadi Anda perlu mengembalikan konstruktor B.Prototipe:
Salin kode sebagai berikut: Fungsi a (name) {
this.name = name;
}
A.prototype.show = function () {
console.log (this.name);
};
fungsi b (name) {
this.name = name;
}
B.Prototype = a.prototype;
B.prototype.constructor = b;
var test = baru b ('test');
test.show ();
Console.log (test.constructor);
Alasan untuk melakukan ini adalah karena nilai prototipe adalah objek, dan fungsi konstruktornya adalah fungsi di mana ia berada, yaitu:
Salin kode sebagai berikut: Console.log (a.prototype.constructor === a);