JS使用call函数实现继承

来源:互联网 发布:数据库表如何设计null 编辑:程序博客网 时间:2024/05/29 13:24

JS是一门轻量级的语言,不支持高级语言的继承语法,但是可以通过call或apply函数(这两个函数实现结果一样,用法略有不同,本文主要讲解call函数的使用方法)实现继承的效果,下面举个例子来讲解。


一、call函数的使用方法

// 基类var father = function() {this.say = function() {alert('父亲');}}// 子类var student = {};// 使用call实现继承father.call(student);student.say();     // -->'父亲'

通过以上例子可以看出,call函数将对象father上的所有属性和函数挂在了student对象上,所以student对象能够直接调用father对象的say()函数,从而实现了继承。


二、call函数调用过程讲解

官方给出的定义是:调用一个对象的一个方法,以另一个对象替换当前对象。 call 方法可以用来代替另一个对象调用一个方法。call 方法可将一个函数的对象上下文从初始的上下文改变为由 thisObj 指定的新对象。

看上去有点抽象,博主个人的理解就是,当father.call(student)时,father就是原对象,student是你要调用的对象,原本指针指向的father对象现在改成了student,即上下文this发生了改变。所以student获得了father对象的所有属性和函数。call函数也可以有多个参数,第一个参数永远是当前调用的对象,用来传递this值。

// 基类var father = function() {this.say = function(x) {alert(x);}}var fa = new father();var student = {};// 使用call实现继承fa.say.call(student, '学生');     // -->'学生'


三、call函数实现多继承

其实很简单,让一个对象中继承多个对象即可,还是举个例子。

// 父亲var father = function() {this.fasay = function() {alert('父亲');}}// 母亲var mother = function() {this.mosay = function() {alert('母亲');}}// 子类var student = function() {    father.call(this);mother.call(this);}// 创建子类对象var student = new student();// 调用母亲对象的方法student.mosay();     // -->'母亲'

1 0