[JavaScript]编写一个b继承a的方法

本文探讨如何在JavaScript中创建一个类B继承自类A的方法,详细阐述了继承的概念和实现步骤,帮助开发者理解JavaScript的面向对象特性。

编写一个b继承a的方法

        function a() {
            this.run = function () {
                return 'a方法';
            }
        }
        function b() {

        }
        b.prototype = new a();
        var objb = new b();
        console.log(objb.run())
JavaScript 中有多种实现继承方法,以下为你介绍几种常见的方法以及在网页上显示继承结果的方式。 ### 基于原型和构造函数实现继承(ES5) ```javascript function A(name) { this.name = name; this.sayHello = function() { return this.name + " say Hello!"; }; } function B(name, id) { A.call(this, name); this.id = id; this.checkId = function(ID) { return this.id === ID; }; } B.prototype = Object.create(A.prototype); B.prototype.constructor = B; // 创建实例 let instanceB = new B("John", 123); // 在网页上显示继承结果 document.write(instanceB.sayHello() + "<br>"); document.write("Check ID result: " + instanceB.checkId(123) + "<br>"); ``` 这种方法通过 `A.call(this, name)` 在子类构造函数中调用父类构造函数,将父类的属性和方法添加到子类实例上,再使用 `Object.create(A.prototype)` 继承父类的原型方法 [^2]。 ### 寄生组合式继承(ES5) ```javascript function A(name) { this.name = name; this.sayHello = function() { return this.name + " say Hello!"; }; } function B(name, id) { A.call(this, name); this.id = id; this.checkId = function(ID) { return this.id === ID; }; } function inheritPrototype(subType, superType) { let prototype = Object.create(superType.prototype); prototype.constructor = subType; subType.prototype = prototype; } inheritPrototype(B, A); // 创建实例 let instanceB = new B("John", 123); // 在网页上显示继承结果 document.write(instanceB.sayHello() + "<br>"); document.write("Check ID result: " + instanceB.checkId(123) + "<br>"); ``` 寄生组合式继承是在组合继承的基础上优化了原型链的创建过程,避免了重复调用父类构造函数 [^1]。 ### 使用 class 语法实现继承(ES6) ```javascript class A { constructor(name) { this.name = name; } sayHello() { return this.name + " say Hello!"; } } class B extends A { constructor(name, id) { super(name); this.id = id; } checkId(ID) { return this.id === ID; } } // 创建实例 let instanceB = new B("John", 123); // 在网页上显示继承结果 document.write(instanceB.sayHello() + "<br>"); document.write("Check ID result: " + instanceB.checkId(123) + "<br>"); ``` ES6 引入了 `class` 关键字和 `extends` 关键字,使用 `super` 调用父类的构造函数,使继承实现更加简洁 [^1]。
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值