JavaScript之繼承

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();
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章