这是我参与8月更文挑战的第5天,活动详情查看:8月更文挑战markdown
一、 原型继承方式app
function Person(name,age){
this.name = name;
this.age = age;
}
Person.prototype.sayHello = function(){
console.log("使用原型获得名字:%s,年龄:%d",this.name,this.age);
}
function Student(){
}
Student.prototype = new Person("Jay",37);
Student.prototype.grade=5;
Student.prototype.tips=function(){
console.log("我是从Student来的,年级是%d,继承来的%s",this.grade,this.name);
}
var stu = new Student();
stu.tips();
复制代码
二、 构造函数方式函数
//父类函数
function Parent(name){
this.name = name;
this.sayHello = function(){
console.log("Parent Name : %s",this.name);
}
}
//子类函数
function Child(name,age){
this.tempMethod = Parent;
this.tempMethod(name);
this.age = age;
this.sayChild = function(){
console.log("Child Name:%s,Age:%d",this.name,this.age);
}
}
//测试继承
var p = new Parent("Kvkens");
p.sayHello();
var c = new Child("Kvkens",29);
c.sayChild();
复制代码
三、 call、apply 方式post
function Animal(name,age,love){
this.name = name;
this.age = age;
this.love = love;
this.sayHi = function(){
console.log("Animal name:%s,age:%d,love:%s",this.name,this.age,this.love);
}
}
function Dog(name,age,love){
Animal.call(this,name,age,true);
}
var dog = new Dog("xiaobai",5,true);
dog.sayHi();
复制代码