头部背景图片
小畅的学习笔记 |
小畅的学习笔记 |

js实现继承

实现两个类 A 和 B, 且B类继承自A类,B类的实例可以调用A类的方法

1. 借用构造函数继承:

用.call()和.apply()将父类构造函数引入子类函数;
call() 方法:B.call(A, args1,args2);即A对象调用B对象的方法;
apply() 方法:用作 this 的对象和要传递给函数的参数的数组 B.apply(A, arguments);即A对象应用B对象的方法

function A(propertyA){
    this.propertyA=propertyA;
    this.fn1 = function(){

    };
}
function B(propertyB){
    A.call(this,args1,args2);//A.apply(this,[])
    this.propertyB = propertyB;
}
var b1 = new B("大毛");  
b.fn1();
2. 原型链继承
function A(propertyA){
    this,propertyA = propertyA;
    this.fn = function(){}
}
function B(propertyB){
    this.propertyB = propertyB;
}
B.prototype = new A("");
var b1 = new B("");
b1.fn();
3. 混合方式:组合继承(组合原型链继承和借用构造函数继承)
function A(propertyA){
    this,propertyA = propertyA;
    this.fn = function(){}
}
function B(propertyB){
    A.call(this,args1,args2);//A.apply(this,[])
    this.propertyB = propertyB;
}

B.prototype = Object.create(A.prototype);//创建一个父类的原型对象,并返回这个新对象
B.prototype.constructor = B;

var B=new B("张");  
b1.fn();
console.log(B instanceof A) //true
4. 对象冒充
function A(){
this.name = "name";
this.sayName = function(){
    console.log(this.name);
    }
}
function B(){
    this.temp = A;//创建对象
    this.temp();//调用方法
    delete this.temp;//删除对象,以免覆盖父类

    this.id = "1";
}
var b = new B();
b.sayName();
Lililich's Blog