js中的私有方法
_privateMethod(){}形式
關(guān)于this
- 函數(shù)中的this指向函數(shù)的調(diào)用者undefined(window)
下述代碼中,報(bào)錯(cuò)原因是對(duì)象外的getAge無(wú)法識(shí)別函數(shù)體內(nèi)的age
class Person{
constructor(){
this.age=12;
}
getAge()
{
return this.age;
}
}
let p=new Person()
let GetAge=p.getAge
GetAge()
// Cannot read property 'age' of undefined
- 用bind改進(jìn)
class Person{
constructor(){
this.age=12;
}
getAge()
{
return this.age;
}
}
let p=new Person()
let GetAge=p.getAge
GetAge.bind(p)//12
- super()
class Stu extends Person{
constructor(){
super();//必須寫(xiě)在第一行
this.age=13
}
}