JS类继承常用方式发展史

来源:互联网 发布:大数据信息贩卖 编辑:程序博客网 时间:2024/05/22 14:22

前言

当JS被创造出来的时候,并没有使用当时最流行的类方式,像(JAVA C++)。具体原因为:

对于有基于类的语言经验的开发人员来说,JavaScript 有点令人困惑 (如Java或C ++) ,因为它是动态的,并且本身不提供一个类实现。(在ES2015/ES6中引入了class关键字,但只是语法糖,JavaScript 仍然是基于原型的)。
参考2

1 构造函数方式继承

1.1 通过构造函数多步骤完成继承单个对象

/** * log-console.log的简单封装插件 *  * @demo log(xxx) ==> console.log(xxx) * @explain 1 可以代替console.log()使用 * @explain 2 可以运行在浏览器环境和NodeJs环境 */function log() {  console.log.apply(console, arguments);}/** * Student--学生抽象类-希望作为其中的一个父类 * @param {String} guide 职业 */function Student({guide}) {  this.guide = guide;}Student.prototype.showGuide = function() {  log(this.guide);}/** * People--子类,希望能够继承Student *  * @want People的实例对象拥有Student的特性,且可以自己扩展 * 扩展后不影响Student */function People(props) {  Student.call(this, props);  this.country = props.country;}/** * 通过中间对象(函数)来实现People正确的原型链指向 *  * @explain step1 MidFn 创建一个空函数 * @explain step2 把MidFn函数的原型指向Student.prototype * @explain step3 把People原型对象指向MidFnde原型对象, MidFn的原型正好指向Student.prototype * @explain step4 把People原型的构造函数修复为People * @explain step5 People扩展方法测试是否会影响Student */// step1function MidFn() {}// step2MidFn.prototype = Student.prototype;// step3People.prototype = new MidFn();// step4People.prototype.construtor = People;// step5People.prototype.showCountry = function() {  log(this.country);}const jeson = new People({  guide: 'web前端',  country: '中国'});jeson.showGuide();jeson.showCountry();log(jeson instanceof People); // => truelog(jeson instanceof Student); // => trueconst student1 = new Student({  guide: '全栈',  country: 'Chinese'});student1.showGuide(); // => '全栈'student1.showCountry(); // => 出错

分析 back

原创粉丝点击