class 使用与构造函数基本相同
1.基本概念
class point {
toString(){}
constructor(){
this.b = 5
this.a = function(){}
}
}
let p = new point()
1.class里的方法都写在原型上 用Object.keys§是检测不到的
2.typeof point ‘function’
3.类内部的方法都是不可枚举的
4.类内部不允许使用严格模式
5.如果一个属性方法没有this,那就是原型上的方法或属性 如上的例子原型上只有一个toString,属性b和方法a可以在实例对象上直接继承,但是要写this,就要在constructor上写
2.类的this指向问题
class point{
constructor(){
this.b = 5
this.a = function(){}
this.printName = this.print.bind(this)
}
print(){
console.log('print')
return 1
}
}
let p = new point()
let result = p.printName
result() // 输出print 返回 1
//这个时候虽然是window在调用该方法,但this被修改指向了point实例
或者使用箭头函数
class point{
constructor(){
this.b = 5
this.a = function(){}
this.printName = () => {this.print()}
}
print(){
console.log('print')
return 1
}
}
let p = new point()
let result = p.printName
result() // 输出print 返回 1
3.类的取值和存值
class point {
toString(){}
get prop(){
return true
}
set prop(value){
console.log(123)
}
}
let p = new point()
console.log(p.prop) // 返回结果为true
p.prop = 5 //输出123 证明函数已经执行了
4.class的静态方法和属性
class point {
toString(){}
constructor(){
this.a = 10
this.b = 20
}
static classMethod(){
return true
}
static h = 50
}
let p = new point()
console.log(p.h) //undefined
p.classMethod() //报错
写了一个static声明后的,就只是class的静态属性,不能被实例对象捕捉到