前 言數組
OOP
閉包JavaScript中OOP——>>>面向對象中的繼承/閉包app
1 // 1.定義父類 2 function Person(name,age){ 3 this.name = name; 4 this.age = age; 5 this.say = function(){ 6 alert(this.name+":"+this.age); 7 } 8 } 9 // 2.定義子類 10 function Student(no){ 11 this.no = no; 12 this.add = function(a,b){ 13 alert(a+b); 14 } 15 } 16 function Programmer(lang){ 17 this.lang = lang; 18 this.codding = function(){ 19 alert("我愛敲代碼!敲代碼使我快樂!"); 20 } 21 } 22 // 3.經過原型給Object對象添加一個擴展方法。 23 Object.prototype.customExtend = function(parObj){ 24 for(var i in parObj){ 25 // 經過for-in循環,把父類的全部屬性方法,賦值給本身 26 this[i] = parObj[i]; 27 } 28 } 29 30 var p = new Person("小明","18"); 31 var s = new Student("0001"); 32 s.customExtend(p);//如今s繼承了p的全部屬性和方法。 33 console.log(s) 34 35 var pro = new Programmer("JavaScript"); 36 pro.customExtend(p); 37 console.log(pro) 38 39 40 41
1 function Person(name,age){ 2 this.name = name; 3 this.age = age; 4 this.say = function(){ 5 alert("我叫:"+this.name+";今年:"+this.age+"歲"); 6 } 7 } 8 9 /** 文檔註釋,調用函數時,能夠看到註釋內容。 10 * 11 * no:學員編號 12 * stuName:學員姓名 13 * stuAge:學員年齡 14 */ 15 function Student(no,stuName,stuAge){ 16 17 this.no = no; 18 Person.call(this,stuName,stuAge); 19 // 執行上述代碼,至關於將下面的代碼執行一遍。而且把原來Person類的this直接替換爲Stundet的this(當實例化Student時的那個對象) 20 21 // this.name = "張三"; 22 // this.age = 14; 23 // this.say = function(){ 24 // alert("我叫:"+this.name+";今年:"+this.age+"歲"); 25 // } 26 } 27 28 var stu = new Student(12,"zhangsan",14); 29 stu.say(); 30 31 console.log(stu) 32 33 //Person("zhangsan","123");
1 function Person(name,age){ 2 this.name = name; 3 this.age = age; 4 this.say = function(){ 5 alert("我叫:"+this.name+";今年:"+this.age+"歲"); 6 } 7 } 8 9 /** 文檔註釋,調用函數時,能夠看到註釋內容。 10 * 11 * no:學員編號 12 * stuName:學員姓名 13 * stuAge:學員年齡 14 */ 15 function Student(no){ 16 this.no = no; 17 } 18 19 Student.prototype = new Person("張三",14) 20 21 var stu = new Student(12); 22 23 stu.say(); 24 25 console.log(stu) 26 27 //Person("zhangsan","123");