本文实例总结了JavaScript类的继承操作。分享给大家供大家参考,具体如下:
一、类式继承
首先要做的是创建构造函数。按惯例,其名称就是类名,首字母应该大写。在构造函数中,创建实例属性要用关键字this
。类的方法则被添加到prototype
对象中。要创建该类的实例,只需结合关键字new
调用这构造函数即可。
/* Class Person. */function Person(name) { this.name = name;}Person.prototype.getName = function() { return this.name;}var reader = new Person('John Smith');reader.getName();
二、原型链
JavaScript的每个对象都有一个名为prototype
的属性,这个属性要么指向另一个对象,要么是null.在访问对象的某个成员时,如果这个成员未见于当前对象,那么就会到prototype所指的对象中去查找。如果还是没有找到,那么就会沿着原型链逐一访问每个原型对象,直到找到这个成员。这意味着让一个类继承另一个类,只需将子类的prototype
设置为超类的一个实例即可。
为了让Author继承Person,必须手工将Author的prototype
设置为Person的一个实例。最后一步是将prototype
的construct
属性重设为Author(因为prototype
属性设置为Person的实例)时,其construct
属性被抹除了。
function Author(name, books) { Person.call(this, name); // Call the superclass' constructor in the scope of this. this.books = books; // Add an attribute to Author.}Author.prototype = new Person(); // Set up the prototype chain.Author.prototype.constructor = Author; // Set the constructor attribute to Author.Author.prototype.getBooks = function() { // Add a method to Author. return this.books;};var author = [];author[0] = new Author('Dustin Diaz', ['JavaScript Design Patterns']);author[1] = new Author('Ross Harmes', ['JavaScript Design Patterns']);console.log(author[1].getName());console.log(author[1].getBooks());
三、extend函数
为了简化类的声明,可以把派生子类的整个过程包装在一个名为extend的函数中。它的作用与其他语言的extend
关键字类似,即基于一个给定的类的结构创建一个新的类:
function extend(subClass, superClass) { var F = function() {}; F.prototype = superClass.prototype; subClass.prototype = new F(); subClass.prototype.constructor = subClass;}
其实所做的事与之前的是一样的。它先设置了prototype
,然后再将其constructor
重设为恰当的值。并且中间利用了一个空函数,这样就可以避免创建超类的实例。使用extend
继承的写法:
function Person(name) { this.name = name;}Person.prototype.getName = function() { return this.name;}/* Class Author. */function Author(name, books) { Person.call(this, name); this.books = books;}extend(Author, Person);Author.prototype.getBooks = function() { return this.books;};
新闻热点
疑难解答
图片精选