ES6 class
发布时间:2020-12-16 04:21:19 所属栏目:百科 来源:网络整理
导读:继承extends 继承可以让子类获得父类的方法 属性 可以扩充 增加新的方法 属性等 class Human { constructor(name,age,sex,hobby) { this .name = name; this .age = age; this .sex = sex; this .hobby = hobby; } desc() { const { name,hobby } = this ; c
继承extends class Human { constructor(name,age,sex,hobby) { this.name = name; this.age = age; this.sex = sex; this.hobby = hobby; } desc() { const { name,hobby } = this; console.log(`我叫${ name },性别${ sex },爱好${ hobby },今年${ age }岁`); } eat() { console.log('吧唧吧唧'); } } class FEEngineer extends Human { constructor(name,hobby,skill,salary) { // 调用父类的构造函数 super(name,hobby); this.skill = skill; this.salary = salary; } say() { console.log(this.skill.join(',')); } } const feer = new FEEngineer( '张四',12'洗澡'],'1k' ); feer.eat(); super ); } checkThis(_this) { 在调用super 父类的this 始终是子类的this console.log(_this === this);true } } 给父类添加了静态属性 Human.total = 899999999; class FEEngineer extends Human { constructor(name,salary) { super(name,1)"> salary; } say() { 非静态方法中访问super -> 父类原型 console.log(super.eat());吧唧吧唧 console.log(super.checkThis(this));undefined console.log(es6,vue,react,webgl } static test() { 在静态方法中访问super -> 父类 console.log(super.name);Human console.log(super.total);899999999 } } const feer = ); feer.say(); FEEngineer.test(); 多态 class Human { say() { console.log('我是人'); } } class Man extends Human { say() { super.say(); console.log('我是小哥哥'); } } class Woman extends Human { say() { super.say(); console.log('我是小姐姐'); } } new Man().say();我是人 我是小哥哥 new Woman().say();我是人 我是小姐姐 重载 class SimpleCalc { addCalc(...args) { if (args.length === 0) { return .zero(); } if (args.length === 1.onlyOneArgument(args); } .add(args); } zero() { return 0; } onlyOneArgument() { return args[0]; } add(args) { 累加 return args.reduce((a,b) => a + b,0function post(url,header,params) { 重载操作 if (!params) { params = header; header = null; undefined } } post('https://imooc.com'2 }); ES5继承的实现 P() { this.name = 'parent'; this.gender = 2this.say = () { console.log('好的好的!我一定到!!咕咕咕'会导致报错,不能调用原型上的方法 P.prototype.test = () { console.log('我是一个test方法'); } C() { 跑一遍父类 P.call(); this.name = 'child'this.age = 11; } var child = C(); child.say();好的好的!我一定到!!咕咕咕 child.test();报错,不能调用原型上的方法 prototype ); } } P.prototype.test = C() { P.call(将C的原型指定为P的属性 C.prototype = P(); 我是一个test方法 babel环境安装 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |