js继承实例

来源:互联网 发布:求生之路2不同网络 编辑:程序博客网 时间:2024/05/22 10:44
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                                                                                                                                                                                                                                                                                                                                                                                                                         
0 0