1. 程式人生 > >自定義型別的建立

自定義型別的建立

建立自定義型別的最常見方式,就是組合使用建構函式模式與原型模式。

 1 window.onload = function() {
 2     var person1 = new Person("Nicholas", 29, "Software Engineer");
 3     var person2 = new Person("Greg", 27, "Doctor");
 4 
 5     person1.friends.push("Van");
 6 
 7     document.writeln("person1.friends : " + person1.friends + "<br />");    //
Shelby,Court,Van 8 document.writeln("person2.friends : " + person2.friends + "<br />"); // Shelby,Court 9 document.writeln("person1.friends === person2.friends : " + (person1.friends === person2.friends) + "<br />"); // false 10 document.writeln("person1.sayName === person2.sayName : " + (person1.sayName === person2.sayName) + "<br />"); //
true 11 }; 12 13 /** 14 * 建構函式模式用於定義例項屬性 15 * @param {string} name 姓名 16 * @param {number} age 年齡 17 * @param {string} job 工作 18 */ 19 function Person(name, age, job){ 20 this.name = name; 21 this.age = age; 22 this.job = job; 23 this.friends = ["Shelby", "Court"]; 24 25 // 動態原型模式,該程式碼只有在初次呼叫建構函式的時候才會執行
26 if (typeof this.sayName !== "function") { 27 Person.prototype.sayName = function() { 28 alert(this.name); 29 } 30 } 31 }

 以上方法,對於有其他OO語言經驗的開發人員去看,比較容易理解,但是效能上並不推薦。因為每次建立新的例項都需要進行一次判斷,哪怕這次的效能損耗是極小的,但畢竟也是有損耗。

我還是將定義方法和共享屬性放在外面,通過原型模型去建立自定義方法,如果有更加優質的程式碼,歡迎分享!

 1 window.onload = function() {
 2     var person1 = new Person("Nicholas", 29, "Software Engineer");
 3     var person2 = new Person("Greg", 27, "Doctor");
 4 
 5     person1.friends.push("Van");
 6 
 7     document.writeln("person1.friends : " + person1.friends + "<br />");    // Shelby,Court,Van
 8     document.writeln("person2.friends : " + person2.friends + "<br />");    // Shelby,Court
 9     document.writeln("person1.friends === person2.friends : " + (person1.friends === person2.friends) + "<br />");    // false
10     document.writeln("person1.sayName === person2.sayName : " + (person1.sayName === person2.sayName) + "<br />");    // true
11 };
12 
13 /**
14  * 建構函式模式用於定義例項屬性
15  * @param {string} name 姓名
16  * @param {number} age  年齡
17  * @param {string} job  工作
18  */
19 function Person(name, age, job){
20     this.name = name;
21     this.age = age;
22     this.job = job;
23     this.friends = ["Shelby", "Court"];
24 
25     // 動態原型模式,該程式碼只有在初次呼叫建構函式的時候才會執行
26     // if (typeof this.sayName !== "function") {
27     //     Person.prototype.sayName = function() {
28     //         alert(this.name);
29     //     }
30     // }
31 }
32 
33 Person.prototype.sayName = function() {
34     alert(this.name);
35 }