class语法
class Dog{
constructor(age){
this.age = age || "2"
}
sayHi(){
console.log("333")
}
}
const D = new Dog()
console.log(D.age) //2
constructor 关键字
constructor 关键字用于在类定义块内部创建类的构造函数,使用new创建实例,会调用constructor 这个函数进行实例化,不定义constructor 相当于构造函数定义为空,一般是在constructor 里定义初始化数据
使用new实例化
class Dog{
constructor(age){
this.age = age || "2"
}
sayHi(){
console.log("333")
}
}
// const D = new Dog()
//如果不使用new 实例化 无法访问 age 属性
console.log(Dog.age) //undefined
使用new实例化Dog等于new调用构造函数 使用new调用类构造函数会执行:
- 在内存中创建一个新对象
- 在这新对象内部[[prototype]]指针被赋值为构造函数的prototype 属性
- 构造函数内部的this被赋值为这个对象
- 给新对象添加属性
静态属性static
用static关键字来声明方法或者属性,该声明无法通过new实例化访问只能通过类名访问
class Dog{
static name = "Memory"
constructor(age){
this.age = age || "2"
}
static hello(){
return "22"
}
sayHi(){
console.log("333")
}
}
const D = new Dog()
console.log(D.name) //undefined
console.log(Dog.name) //Memory
static定义的属性和方法是定义在类的本身,在constructor 里,
没有用static定义
extends关键字
使用extends关键字继承任何拥有[[constructor]]和原型的对象,不仅能继承一个类 还能继承普通函数
class Dog{
static sname = "Memory"
constructor(age){
this.age = age || "2"
}
static hello(){
return "22"
}
sayHi(){
console.log("333")
}
}
class Childs extends Dog{
constructor(){
super()
}
}
//普通函数
// function sayName(){
// }
继承普通函数
// class Name extends sayName{
// }
const C = new Childs()
console.log(C.age) //2
console.log(C.sname) //undefined 子类通过实例也是无法访问父类的静态属性
console.log(Childs.sname) //Memory 子类也是只能通过子类名来访问父类的静态属性
标题super关键字
使用super关键字引用原型,super只能在继承类的构造函数、静态方法使用,
1、在构造函数里使用,可以调用父类的构造函数
class Childs extends Dog{
constructor(){
/* 在super之前引用this会报错Uncaught
ReferenceError: Must call super constructor in derived
class before accessing 'this' or returning from derived constructor
*/
// console.log(this)
/*
在构造函数里使用
*/
super()
console.log(this)
}
}
2、在静态属性方法使用
class Childs extends Dog{
static identify(){
super.hello()
}
}
const C = new Childs()
console.log(C)
console.log(C.age) //2
console.log(C.sname) //undefined 子类通过实例也是无法访问父类的静态属性
console.log(Childs.sname) //Memory 子类也是只能通过子类名
Childs.identify() //被字类的静态属性通过super调用