1.原型鏈繼承
Person.prototype.age = 18;
function Person(){
}
function Student(){
}
var p = new Person();
Student.prototype = p;
var s = new Student();
console.log(s.age);//18
2.call apply繼承
function Person(name,age){
this.name = name;
this.age = age
}
function Student(grade,name,age){
Person.call(this,name,age)
//Person.apply(this,[name,age])
this.grade = grade
}
var s = new Student(100,"xy",18)
console.log(s);//{name: "xy", age: 18, grade: 100}
call apply 的區別
共同:
1.都是要改變this指向
2.第一個參數是this要指向的對象
3.都可以利用後續的參數
不同 :
1.call方法參數將依次傳遞給借用的方法做參數 可以有n個
2.apply方法第一個參數是一個對象 第二個參數是一個僞數組argnments
3.共享原型繼承
Person.prototype.age = 18;
function Person(){
}
function Student(){
}
function extend(Target,Origin){
Target.prototype = Origin.prototype
}
extend(Student,Person);
var s = new Student();
console.log(s.age)//18
缺點:如果Student想在自己的原型上增加新的屬性,Person也會被影響。看例子:
Person.prototype.age = 18;
function Person(){}
function Student(){}
function extend(Target,Origin){
Target.prototype = Origin.prototype
}
extend(Student,Person);
Student.prototype.sex = "male"
var s = new Student();
console.log(s.sex)//male
var p = new Person();
console.log(p.sex)//male 被影響了
4.聖盃模式
這種聖盃模式的本質在於,中間生成了一個對象,起到了隔離的作用,今後爲Son.prototype添加屬性時,全部都會加在這個對象裏面,所以不會對父級產生影響。而向上查找是沿着__proto__查找,可以順利查找到父級的屬性,實現繼承。
function Father(){}
function Son(){}
Father.prototype.lastName='Jack';
function inherit(Target,Origin){
function F(){};
F.prototype=Origin.prototype;
Target.prototype=new F();
Target.prototype.constructor=Target;
Target.prototype.uber=Origin.prototype;
}
inherit(Son,Father);
var son=new Son();
var father=new Father();
Son.prototype.sex="male";
console.log(son.lastName);//Jack
console.log(son.sex);//male
console.log(father.sex);//undefined
Target.prototype.constructor=Target;
由於Target.prototype指向的是objF,因此並沒有constructor這一屬性,沿着__proto__向上查找,發現constructor指向的是Father,因此這裏可以進行歸位,讓它的constructor重新指向它自己
Target.prototype.uber=Origin.prototype;
//uber是超類的意思,這裏主要用來儲存這個目標到底繼承自誰,可寫可不寫
5.ES6–Class繼承
class Person{
constructor(name, age) {
this.name = name;
this.age = age;
}
sayName(){
console.log("the name is:"+this.name);
}
}
class Worker extends Person{
constructor(name, age,job) {
super(name, age);
this.job = job;
}
sayJob(){
console.log("the job is:"+this.job)
}
}
var worker = new Worker('tcy',20,'teacher');
worker.sayJob();//the job is:teacher
worker.sayName();//the name is:tcy