JavaScript之继承

来源:互联网 发布:网络语音肝是啥意思 编辑:程序博客网 时间:2024/06/09 15:08

JavaScript之继承

js的继承_基于原型链方式的继承

var Person = {    name: "李华",    say: function () {        alert(this.name);    }}function clone(obj) {    var F = function () {};    F.prototype = obj;    return new F();}var Student = clone(Person);Student.no = "";Student.books = [];Student.say = function () {    alert(this.no + "  " + this.name);}Student.showBooks = function () {    alert(this.books);}var stu1 = clone(Student);stu1.no = "001";stu1.name = "凯乐"stu1.books.push("java");stu1.say();stu1.showBooks();var stu2 = clone(Student);stu2.no = "002";stu2.name = "王明"stu2.books.push("JavaScript");stu2.say();stu2.showBooks(); //结果是:java JavaScript

这里写图片描述

js的继承_基于类声明的方式的继承

比较好的继承方式,不过对于初学者可能会比较难理解
涉及到call、prototype等知识。

var People = function (name, age) {    this.name = name;    this.age = age;    this.books = [];}People.prototype.say = function () {    alert(this.name + " " + this.age + " " + this.books);}People.prototype.getBooks = function () {    return this.books;}var Student = function (name, age, no) {        this.no = no;        Student.parentClass.constructor.call(this, name, age);    }    //使用extend方法完成继承extend(Student, People);/**********用extend方法*************/function extend(childClass, parentClass) {    var F = function () {};    F.prototype = parentClass.prototype;    childClass.prototype = new F();    childClass.parentClass = parentClass.prototype;}var stu1 = new Student();stu1.name = "小二";stu1.age = 22;stu1.books.push("java");stu1.say();var stu2 = new Student();stu2.name = "大宝";stu2.age = 34;stu2.books.push("HTML");stu2.say();
1 0