這是我參與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();
複製代碼