ES6学习笔记——类
在 ES6 之前,我们通过构造函数来创造一个类,并且通过原型来扩展属性:
1 2 3 4 5 6 7 8 9 | function Person(name, age, gender) { this .name = name; this .age = age; this .gender = gender; } Person.prototype.incrementAge = function () { return this .age += 1; }; |
然后可以这样继承类:
1 2 3 4 5 6 7 8 9 10 11 12 13 | function Personal(name, age, gender, occupation, hobby) { Person.call( this , name, age, gender); this .occupation = occupation; this .hobby = hobby; } Personal.prototype = Object.create(Person.prototype); Personal.prototype.constructor = Personal; Personal.prototype.incrementAge = function () { Person.prototype.incrementAge.call( this ); this .age += 20; console.log( this .age); }; |
在 ES6 中,提供了更多的语法糖,可以直接创造一个类:
1 2 3 4 5 6 7 8 9 10 11 | class Person { constructor(name, age, gender) { this .name = name; this .age = age; this .gender = gender; } incrementAge() { this .age += 1; } } |
使用 extends 关键字来继承一个类:
1 2 3 4 5 6 7 8 9 10 11 12 13 | class Personal extends Person { constructor(name, age, gender, occupation, hobby) { super (name, age, gender); this .occupation = occupation; this .hobby = hobby; } incrementAge() { super .incrementAge(); this .age += 20; console.log( this .age); } } |
手机阅读请扫描下方二维码:
上一篇:移动端小总结
下一篇:ThreeJS学习笔记(三)——三维空间用户交互与动画
12345678

1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
12345678

12345678
12345678
12345678
12345678
12345678

12345678

12345678

1

1

1

1

1

1

1

1

1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1