Js面向对象整理(三)
【摘要】 本篇记录个人所学Js面向对象整理(三),设计知识点:Es6类、类继承extends
Js面向对象(三)
ES6中的类
class 声明创建一个基于原型继承的具有给定名称的新类。
class写法
class Person { static feature = "love&peace"; constructor(options) { this.name = options.name; this.age = options.age; } canDo() { console.log("I can do anything!"); } } let rocky = new Person({ name: "Rocky", age: 24 }); console.log(rocky); rocky.canDo(); let sunny = new Person({ name: "Sunny", age: 18 }); console.log(sunny); sunny.canDo(); console.log(Person.feature);
对比构造函数写法
function Person(options) { this.name = options.name; this.age = options.age; } Person.prototype.canDo = function() { console.log("I can do everything!"); } Person.feature = "peace&love"; let rocky = new Person({ name: "Rocky", age: 24 }); console.log(rocky); rocky.canDo(); let sunny = new Person({ name: "Sunny", age: 18 }); console.log(sunny); sunny.canDo(); console.log(Person.feature);
Es6类的继承:extends
class Cat { static feature = "nine lives"; constructor(name) { this.name = name; this.leg = 4; } climb() { console.log("climb grass..."); } } class Tiger extends Cat { constructor(name) { super(name); } climb() { super.climb(); console.log("climb tree..."); } } let tigger = new Tiger("Tigger"); console.log(tigger); tigger.climb(); let kitty = new Cat("Kitty"); console.log(kitty); kitty.climb(); console.log(Tiger.feature);
END
【版权声明】本文为华为云社区用户原创内容,转载时必须标注文章的来源(华为云社区)、文章链接、文章作者等基本信息, 否则作者和本社区有权追究责任。如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱:
cloudbbs@huaweicloud.com
- 点赞
- 收藏
- 关注作者
评论(0)