前 言数组
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");