class不存在变量提升
静态方法可以被继承(但实例对象不能调用)
注意,如果静态方法包含this关键字,这个this指的是类,而不是实例。
class Person{
//构造方法
constructor(name){ //创建实例的时候自动调用
this.name=name;
}
//公用方法
say(){
console.log('say ...')
}
//静态方法可以被继承(但实例对象不能调用)
static speak(){
console.log('speak')
}
}
let p1=new Person('zhangsan');
Person.speak()
p1.speak();//Uncaught TypeError: teach.speak is not a function 静态方法实例不能调用
//类的继承
class Teach extends Person{
constructor(age){
super(); //继承父类的this
this.age=age;
}
}
let t1=new Person('test');
Teach.speak() //调用继承的静态方法
下面代码可以看出类实质上就是一个函数。类自身指向的就是构造函数。所以可以认为ES6中的类其实就是构造函数的另外一种写法!
typeof Person; //"function"
Person.prototype.constructor.name;//"Person"
teach instanceof Person; //true
teach.__proto__==Person.prototype; //true
Person.prototype.run=function (){
console.log('run')
}
teach.run() //run
constructor
constructor
方法是类的默认方法,通过new命令生成对象实例时,自动调用该方法。一个类必须有constructor方法,如果没有显式定义,一个空的constructor方法会被默认添加。
constructor方法默认返回实例对象(即this),完全可以指定返回另外一个对象。
class Foo {
constructor() {
return Object.create(null);
}
}
new Foo() instanceof Foo // false
静态方法调用
class Person {
static a(){
console.log(this.prototype)
//静态方法中调用非静态方法
console.log(this.prototype.c())
}
static b(){
Person.a() //静态方法中调用静态方法
console.log('bbbbbb.............')
}
c(){
console.log('ccc')
}
}
Person.a()
静态属性
class Person{
name=123;
static name1='aa'; //设置静态属性
constructor() {
}
}
var teach=new Person();
console.log(teach.name) //123
console.log(teach.name1) //undefined
console.log(Person.name1) //aa