js继承实例

1.js原型(prototype)实现继承
function Person(name, age){
  this.name = name;
  this.age = age;
}
//给它的原型直接添加属性或方法
Person.prototype.love = "alin";
Person.prototype.sayHello = function(){
  console.log(this.name);//lilinwei
}
var per = new Person("lilinwei", 2);
per.sayHello();
console.log(per.love);//alin
function Student(){ }
Student.prototype = new Person("Leeon", 22);
Student.prototype.grade = 4;
Student.prototype.intr = function(){
  console.log(this.grade);
}
var stu = new Student();
stu.sayHello();//Leeon
stu.intr();//4      
2.构造函数继承
function Parent(name){
  this.name = name;
  this.sayName = function(){
  console.log("Parent:" + this.name);
  }
}
function Child(name, age){
  this.tempMethod = Parent;
  this.tempMethod(name);
  this.age = age;
  this.sayName = function(){
  console.log("Child" + this.name + "age" + this.age);
  }
}
var parent = new Parent("zzl");
parent.sayName();//zzl
var child = new Child("llw", 2);
child.sayName();//llw 2    
3.call/apply
function Person(name, age){
  this.name = name;
  this.age = age;
  this.say = function(){
  console.log("姓名:" + name);
  }
}
//call
function Student1(name, age){
  Person.call(this, name, age);
}
//apply
function Student2(name, age){
  Person.apply(this, [name, age]);
  //Person.apply(this, arguments);等价于上一句
}
var per = new Student1("zzl", 88);
per.say();//姓名:zzl                                                                                                                                                                                                                                                                                                                                                                                                                         
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值