继承普通版
继承逻辑上都差不多,普通版调用方式比较繁琐,不利于反复大量的使用;
(function (){ //创建一个人员类 function Person(name){ this.name = name; } //创建教师类 function Teacher(name,books){ //call方法可以将一个函数的对象上下文从初始化变成由this来决定; //调用person的构造函数,因为person没用new,所以他是个空对象; //相当于Java中的super函数; Person.call(this,name); this.books = books; } //使老师类继承人员类; Teacher.prototype = new Person(); Teacher.prototype.constructor = Teacher; Teacher.prototype.getBook = function(){ return this.name + ' ' + this.books; } //测试 var victor = new Teacher('victor','chinese'); alert(victor.getBook());})()
继承升级版
(function (){ //创建一个人员类 function Person(name){ this.name = name; } //创建教师类 function Teacher(name,books){ //call方法可以将一个函数的对象上下文从初始化变成由this来决定; //调用person的构造函数,因为person没用new,所以他是个空对象; //相当于Java中的super函数; Person.call(this,name); this.books = books; } /*创建Extend函数是为了程序中所有的继承操作*/ function extend(subClass,superClass){ //1.让子类的原型类属性等于父类的原型属性 //初始化一个中间空对象,为了转换主父类关系 var F = function(){}; F.prototype = superClass.prototype; //2.让子类继承F; subClass.prototype = new F(); subClass.prototype.constructor = subClass; //3.为子类增加属性superClass subClass.superClass = superClass.prototype; //4.增加一个保险,就算是原型类的超类(object)那么也要把你的构造函数级别降下来 if ( superClass.prototype.constructor == Object.prototype.constructor ) {//Object为超类,首字母需要大写 superClass.prototype.constructor = superClass; } } //测试 function Author(name,books){ Author.superClass.constructor.call(this,name); this.books = books; this.getBook = function(){ return this.name + ',' + this.books; } } //继承 extend(Author,Person); var victor = new Author('victor','javascript'); alert(victor.getBook()); })()