JavaScript 面向对象编程,主要就是搞清楚原型继承的问题。下面举两个例子说明一下:
原始方式
//创建父类
var Book = function(props){
this.name = props.name || '书';
this.year = props.year || 0;
this.author = props.author || '侠名';
}
//在原型上定义共享函数
Book.prototype.sayName = function(){
console.log( this.name );
}
//创建子类
var StoryBook = function(props){
Book.call(this, props);//"继承"构造函数 Book
this.kind = 'StoryBook';
this.pages = props.pages || 0;
}
//继承函数
var inherits = function(Child,Parent){
var F = function(){};
F.prototype = Parent.prototype;
Child.prototype = new F();
Child.prototype.constructor = Child;
}
//继承
inherits(StoryBook,Book);//继承父类
//创建实例
var book_theThreeKingdoms = new StoryBook({name:'三国演义'});
console.log( book_theThreeKingdoms.name );//三国演义
ES6 class
ES6 中的 class
实现继承,class
的方式实现继承,和上面的方法实际上是一样的,只不过通过class
大大简化操作,也让代码更易读。
//创建父类,定义共享函数
class Book{
//构造函数
constructor(props){
this.name = props.name || '书';
this.year = props.year || 0;
this.author = props.author || '侠名';
}
//共享函数
sayName(){
console.log( this.name );
}
}
//创建子类,继承父类
class StoryBook extends Book{
constructor(props){
super(props);//调用父类的构造方法
this.kind = 'StoryBook';
this.pages = props.pages || 0;
}
}
//创建实例
var book_theThreeKingdoms = new StoryBook({name:'三国演义'});
console.log( book_theThreeKingdoms.name );//三国演义