Es6 的语法糖,简化了上一篇的写法,让程序码更好阅读
这边改写前一篇介绍过的例子
Before:
/*function Person(name,sex,age){
console.log(this); // {}
this.name = name;
this.sex = sex;
this.age = age;
}
Person.prototype.sayHi= function(){
console.log(this.name+" says Hi");
}*/
After:
class Person{
constructor(name,sex,age){
this.name = name;
this.sex = sex;
this.age = age;
}
sayHi(){
console.log(this.name+" says Hi");
}
}
let Helen = new Person("Helen","Female",24);
console.log(Helen)
let Daniel = new Person("Daniel","Male",23);
console.log(Daniel);
console.log(Helen.sayHi == Daniel.sayHi);
Helen 和 Daniel 都从同一个 prototype 去继承 sayHi()
当我们要建立一个新的 function,并和 Person 共用参数时
Before:
/*function Student(name,sex,age,height,weight){
Person.call(this,name,sex,age);
this.height;
this.weight;
}
Student.prototype = Object.create(Person.prototype);
Student.prototype.study = function(){
console.log("I am studying")
}
let Daniel = new Student("Daniel","Male",23,172,56);
console.log(Daniel);
Daniel.sayHi(); // Daniel says Hi
Daniel.study(); // I am studying*/
After:
使用 extends 继承 Person,super 是集合的概念(和离散数学有关)
class Person{
constructor(name,sex,age){
this.name = name;
this.sex = sex;
this.age = age;
}
sayHi(){
console.log(this.name+" says Hi");
}
}
class Student extends Person{
constructor(name,sex,age,height,weight) {
super(name,sex,age);
this.height = height;
this.weight = weight;
}
study(){
console.log("I am studying")
}
}
let Helen = new Student("Helen","Female",24,160,56);
console.log(Helen);
Helen.sayHi(); // Helen says Hi
Helen.study(); // I am studying
此时可以看到 Helen 的 prototype 里不但有 study(),也继承了 Person 里 prototype 的 sayHi()
Static Properties and Methods 不是属於 class 内所做出来的 object,而是属於 class,任何 Properties and Methods 只要设成 static,他们就会属於 class。
以计算圆面积和周长的例子来看,
Before:
/*
class Circle{
constructor(radius){
this.radius = radius;
}
getArea(){
return this.radius * this.radius * 3.14;
}
getPerimeter(){
return 2 * 3.14 * this.radius;
}
}
let circle1 = new Circle(5);
console.log(circle1); // 78.5
*/
因为 pi 是固定的,我们其实不需要在每个 function 都写上 3.14,这时候可以使用 static,让那些固定不变的 property 或 method 属於 class。
After:
class Circle{
static pi = 3.14;
constructor(radius){
this.radius = radius;
}
getArea(){
return this.radius * this.radius * Circle.pi;
}
getPerimeter(){
return 2 * Circle.pi * this.radius;
}
static getAreaFormula(){
console.log("r * r * 3.14")
}
}
Circle.getAreaFormula(); // r*r*3.14
let circle1 = new Circle(10);
console.log(circle1.getArea()); // 314
>>: Day 10【连动 MetaMask - Login Flow & Extension Check】The strongest password ever.
Python的程序有2种退出方式:os._exit(), sys.exit() os._exit()...
-CBC-MAC(来源:https : //en.wikipedia.org/wiki/CBC-M...
「我们公司做的是接案,跟 Scrum 的迭代精神不符,还适合用 Scrum 开发吗?」 这个问题的雷...
除了刷题之外的事 刷题是练习解决问题的能力的一种方法,而这里的「问题」主要是指演算法问题。但在实务...
Template variable 可以让你在 template 的任意一处使用被标记过的 HTML...