声明类:(类名首字母要大写)
//命名类
class Person{
}
定义类:
//匿名类
var fn=class Person{
this.a=a
}
var f1=fn
console.log(f1)
属性:ES6的类中不能直接定义变量,变量被定义在constructor中。一个类中有且仅有一个构造方法。
具体实例看下:
class Person{
constructor(a,b,c){
console.log(666666)
this.x=a
this.b=b
}
//对象的属性,原型
life=50
//对象的原型对象的方法,原型
say1(){
console.log(111,this.x)
}
//类的静态属性
static life=200
//类的静态方法
static say2(){
console.log(222)
}
}
var p1=new Person(10,20,30)
//Person类的内部可以写一个constructor方法 用这个类创建对象时 就会运行构造函数
//不写构造函数 系统会默认有一个空的构造运行
console.log(p1)
console.log(Person.life)
console.log(Person.say2)
可以参照一下不用类的原始方法:
//不用类的原始方法
function Person1(a,b,c){
console.log(666666)
this.x=a
this.b=b
}
Person1.prototype.say=function(){}
Person1.life=1
Person1.say2=function(){
console.log(222)
}
var p2=new Person1(10,20,30)
继承:
//父
class Person {
life = 1
constructor(name) {
this.name = name
this.makeMoney = function() {
console.log(this.name + "赚钱")
}
}
run() {
console.log(this.name + "跑步")
}
static URL = "www"
}
var p1 = new Person("karen")
var p2 = new Person("jack")
console.log(p1, p2, Person.URL, 11111)
//子
class Student extends Person {
constructor(name) {
super(name) //让Person类的构造函数的逻辑去帮我们构建对象空间
this.age = 20
this.book = "书名"
}
}
如上可见:class 子 extends 父{ }
子中要有super来让父中的构造函数的逻辑来构造对象空间