1.定义类
class Person { // class打头 定义一个类
constructor(name,age,job){ // constructor 定义一个构造方法
this.name = name;
this.age = age;
this.job = job;
this.friend = ['Shelby','Court'];
}
sayName () { // 声明一个方法
console.log(this.name);
}
}
let person = new Person('张三',26,'司机');
person.sayName();
注:ES6中没有方法的重载,即同名函数,后面会覆盖掉前面的。
2.静态方法:(方法名前面加 static,可以用类名调用的方法,我们称之为静态方法)
class Point {
constructor(x,y){
this.x = x; // 在类里面,this.xxx = xxx 必须要放在构造方法中
this.y = y;
}
static distance(a,b) { // 方法名前面加 static
const dx = a.x - b.y;
const dy = a.y - b.y;
return Math.sqrt(dx*dx + dy*dy); // sqrt 开平方
}
}
let point1 = new Point(3,4);
let point2 = new Point(18,24);
let dis = Point.distance(point1,point2); // 使用类名调用静态方法
alert(dis);
3.ES6明确规定,Class内部只有静态方法,没有静态属性,但可以用另外方式解决(将类视为一个对象,给对象加参数)。
class Foo {
}
Foo.prop =1; // 将类视为一个对象,给对象加参数
Foo.prop // 1
//-------单例模式 (有且只有一个)
class Cache {
static getInstance () {
if(!Cache.instance){
Cache.instance = new Cache();
}
return Cache.instance;
}
}
var cache = Cache.getInstance();
实例:
4.继承:
class Animal {
constructor(name){
this.name = name;
}
speak() {
console.log(this.name + 'makes a noise');
}
}
class Dog extends Animal { // 继承 只有单继承,没有多继承
speak() { // 重写speak
console.log(this.name + 'barks');
}
}
let dog = new Dog('旺财');
dog.speak();
// 狗barks
// 如果Dog里没有speak,则 狗 makes a noise
.