JS继承

  1.js原型(prototype)实现继承

function person(name, age) {
     this.name = name;
     this.age = age;
     this.child = [1,2];
 }
 person.prototype.say = function() {
     alert("使用原型得到Name:" + this.name)
 }
 //var per = new person("cherry", 22);
 //per.say();
 
 function Student() {}
 Student.prototype = new person("cherryStu", 23);//原型继承person类并初始化,不可多重继承
 Student.prototype.grade = 3;//定义新的属性
 Student.prototype.init = function() { //定义新的方法
     alert(this.child);
 }
 var stu = new Student();
 //stu.say(); //父类方法可以调用
 stu.init(); //1,2
 
 var stu2 = new Student();   //缺点:当有子类有多个实例时,其中一个实例改变父类中的属性值,其他子类跟着变化
 stu.child.push(3);
 stu2.init();//1,2,3
 stu.init();//1,2,3

 2.构造函数实现继承

function  Parent(name){
     this.name=name;
     this.sayParent = function() {
         alert("Parent:"+this.name);
     }
 }
//缺点:父类方法如改成这样定义,则子类在用构造函数继承时不能调用
 //Parent.prototype.sayParent = function() {
 //    alert("Parent:"+this.name);
 //}

 function Child(name, age) {
     this.tempMethod = Parent; //tempMethod为自定义名字, 这里使用了构造函数继承 对象冒充
     this.tempMethod(name);
     this.age = age;
     this.sayChild = function() {
         alert("Child:" + this.name + " age:" + this.age);
     }
 }
 var par = new Parent("Father");
 par.sayParent();
 var child = new Child("Lucy", 22);
 child.sayChild();

  3.call , apply实现继承

function Person(name, age, love) {
     this.name = name;
     this.age = age;
     this.love = love;
     this.say = function say() {
         alert("姓名:" + name + " 年龄:" + age + " 爱人:" + love);
     }
 }
 function Student(name, age) {
     Person.call(this, name, age);
 }
 function Teacher(name, age) {
     Person.apply(this, [name, age]);
 }
 var per = new Person("武凤楼", 25, "魏荧屏");
 per.say();
 var stu = new Student("曹玉", 18);
 stu.say();
 var tea = new Teacher("秦杰", 16);
 tea.say();

4.原型继承和构造函数继承混合

171909_NNY5_989269.png


转载于:https://my.oschina.net/cherryzhang/blog/601953

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值