1:类式继承
// 声明父类
function Farent(name) {
this.name = name;
this.books = ["JS","php"];
}
// 给父类添加一个共有方法 在父类的原型上
Farent.prototype.getName = function() {
console.log(this.name);
}
// 声明子类
function Child(age) {
this.age = age;
}
// 给子类添加一个共有方法 在子类的原型上
Child.prototype.getAge = function(){
console.log(this.age);
}
// 继承父类
Child.prototype = new Farent("父类");
var c = new Child("18");
// 调用父类的方法
c.getName() // 父类
var c1 = new Child("28");
var c2 = new Child("28");
c1.push("设计模式");
console.log(c2.books); // ["JS","php","设计模式"];
注 : 类式继承其实很简单 ,就是先声明两个类 , 然后将 父类的实例赋值给 子类的原型。
缺点: 多次实例化后 , 修改其中的一个 , 其他的也会跟着变 ! (这不是我们想要的)
、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、
2:构造函数继承
// 声明父类
function Farent(id){
this.books = ['JavaScript','PHP','Python'];
this.id = id;
}
// 父类声明原型方法
Farent.prototype.getBooks = function() {
console.log(this.books);
}
// 声明子类
function Child(id) {
// 继承父类
Farent.call(this,id)
}
// 创建两个子类的 实例
var c1 = new Child("2018");
var c2 = new Child("2019");
c1.books.push("go");
console.log(c1.books); // ["JavaScript", "PHP", "Python", "go"]
console.log(c2.books); // ["JavaScript", "PHP", "Python"]
console.log(c1.id); // 2018
console.log(c2.id); // 2019
c1.getBooks(); // 报错 TypeError
优点:多次实例化后 ,改变其中一个值 , 其他的不会跟着变
缺点:这种类型的继承 没有涉及到 原型( prototype ),所以父类的原型方法自然不会被 子类所继承 !
、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、
重点来了 , 我们可以把这两个的优点组合一起来使用 …
3: (1,2) 优点为我所有 — 组合继承
// 声明父类
function Farent(name){
this.books = ['JavaScript','PHP','Python'];
this.name = name;
}
// 父类声明原型方法
Farent.prototype.getName = function() {
console.log(this.name);
}
// 声明子类
function Child(name,time) {
// 继承父类
Farent.call(this,name)
this.time = time;
}
// 继承父类
Child.prototype = new Farent("父类");
// 给子类添加一个共有方法 在子类的原型上
Child.prototype.getTime = function(){
console.log(this.time);
}
var c1 = new Child("JS book" ," 2015 ");
c1.push("设计模式");
console.log(c1.books) // ['JavaScript','PHP','Python','设计模式'];
var c2 = new Child("python book" ," 2017");
console.log(c2.books) // ['JavaScript','PHP','Python'];
c2.getName(); // python book
c2.getTime(); // 2017
优点:
1:子类的实例化过去 能将参数传递给 父类。
2:多次实例化子类 改变其中一个 , 其他的实例化 不会改变 !
缺点 : 因为每次子类在实例化时 , 父类的构造函数 就会被调用一次 !
、、、、、、、、、、、、、、、/、、、、、、、、、、、、、、、、、、、、、、、
别着急 后面还有更好的继承方式…………
版权声明:本文为shaowei828原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。