jQuery继承是JavaScript继承的一种实现方式,它允许一个对象获取另一个对象的属性和方法,在jQuery中,我们可以通过以下几种方式实现继承:
1、原型链继承:这是JavaScript继承的基本方式,通过将子类的原型设置为父类的实例来实现,在jQuery中,我们可以使用$.extend()
方法来实现原型链继承。
function Parent() { this.name = 'parent'; } Parent.prototype.sayName = function() { console.log(this.name); }; function Child() { Parent.call(this); } Child.prototype = new Parent(); var child = new Child(); child.sayName(); // 输出 'parent'
2、构造函数继承:这种方式是通过在子类构造函数中调用父类构造函数来实现的,在jQuery中,我们可以使用$.fn.extend()
方法来实现构造函数继承。
function Parent() { this.name = 'parent'; } Parent.prototype.sayName = function() { console.log(this.name); }; function Child() { Parent.apply(this, arguments); } $.extend(Child.prototype, Parent.prototype); var child = new Child(); child.sayName(); // 输出 'parent'
3、组合继承:这种方式是将原型链继承和构造函数继承结合起来,使得子类既继承了父类的属性和方法,又能够接收到父类传递的参数,在jQuery中,我们可以使用$.extend()
方法和$.fn.extend()
方法来实现组合继承。
function Parent() { this.name = 'parent'; } Parent.prototype.sayName = function() { console.log(this.name); }; function Child() { Parent.apply(this, arguments); } Child.prototype = new Parent(); Child.prototype.constructor = Child; // 修复原型链指向问题 $.extend(Child.prototype, Parent.prototype); // 实现原型链继承 $.fn.extend(Child.prototype, Parent.prototype); // 实现构造函数继承 var child = new Child(); child.sayName(); // 输出 'parent'
4、寄生继承:这种方式是在子类原型上添加父类的方法,而不是在子类原型上扩展父类,这样可以避免修改父类的原型,同时可以实现复用,在jQuery中,我们可以使用$.extend()
方法来实现寄生继承。
function Parent() { this.name = 'parent'; } Parent.prototype.sayName = function() { console.log(this.name); }; function Child() { } $.extend(Child.prototype, Parent.prototype); // 实现寄生继承,将父类的方法添加到子类原型上,但不改变父类的原型结构 Child.prototype.sayHello = function() { // 子类自己的方法,不会影响到父类的方法调用顺序和属性访问顺序等特性 console.log('hello'); }; var child = new Child(); child.sayName(); // 输出 'parent',因为寄生继承将父类的方法添加到了子类原型上,所以可以直接调用父类的方法,而不需要再通过super
关键字来调用父类的方法,由于子类没有自己的name
属性,所以这里输出的是undefined
,如果需要让子类有自己的name
属性,可以在子类的构造函数中添加相应的代码。Child.prototype.constructor = Child; Child.prototype.name = 'child';
,然后再次运行上述代码,就可以输出正确的结果了,由于寄生继承不会改变父类的原型结构,所以子类无法访问到父类的私有属性和方法(如_name
、_sayName
),如果需要让子类访问到这些私有属性和方法,可以使用其他方式来实现继承,组合继承、原型链继承等。