JavaScript Object Constructors
一個 JavaScript Object Constructor (Function Constructor) 範例如下
function Person(first, last, age, eye) { this.firstName = first; this.lastName = last; this.age = age; this.eyeColor = eye; } var myFather = new Person("John", "Doe", 50, "blue"); var myMother = new Person("Sally", "Rally", 48, "green"); console.log(myFather.firstName); console.log(myMother.firstName);
Function Constructor 利用 this 這關鍵字來建構自己的屬性,
Function Constructor 是一個 object,而你在使用時會覺得 Person 像是個 class。
你可以在已宣告的變數 myFather 或 myMother 添加額外屬性
function Person(first, last, age, eye) { this.firstName = first; this.lastName = last; this.age = age; this.eyeColor = eye; } var myFather = new Person("John", "Doe", 50, "blue"); var myMother = new Person("Sally", "Rally", 48, "green"); console.log(myFather.firstName); console.log(myMother.firstName); myFather.nationality = "English"; console.log(myFather.nationality);
但不可以在 Person 的 Constructor 以下面方式添加額外屬性,雖然不會報錯,
但 myFather 或 myMother 物件也不會有 nationality 屬性
function Person(first, last, age, eye) { this.firstName = first; this.lastName = last; this.age = age; this.eyeColor = eye; } var myFather = new Person("John", "Doe", 50, "blue"); var myMother = new Person("Sally", "Rally", 48, "green"); console.log(myFather.firstName); console.log(myMother.firstName); Person.nationality = "English"; console.log(myFather.nationality);
JavaScript 內建了以下 Constructors
var x1 = new Object(); // A new Object object var x2 = new String(); // A new String object var x3 = new Number(); // A new Number object var x4 = new Boolean(); // A new Boolean object var x5 = new Array(); // A new Array object var x6 = new RegExp(); // A new RegExp object var x7 = new Function(); // A new Function object var x8 = new Date(); // A new Date object console.log(typeof x1); console.log(typeof x2); console.log(typeof x3); console.log(typeof x4); console.log(typeof x5); console.log(typeof x6); console.log(typeof x7); console.log(typeof x8);
但在大部份情況,則不需要用 object 這麼複雜的作法來處理,使用以下方式更為直覺快速
var x1 = {}; // new object var x2 = ""; // new primitive string var x3 = 0; // new primitive number var x4 = false; // new primitive boolean var x5 = []; // new array object var x6 = /()/ // new regexp object var x7 = function () { }; // new function object console.log(typeof x1); console.log(typeof x2); console.log(typeof x3); console.log(typeof x4); console.log(typeof x5); console.log(typeof x6); console.log(typeof x7);