JavaScript之继承

本文介绍了JavaScript中两种实现继承的方法:基于原型链的继承和基于类声明的继承。通过具体示例展示了如何使用这两种方法来创建继承关系,并讨论了它们的特点。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值