整理下之前做的有点疑惑的js基础题目和大家分享以下,如果大家觉得有用,别忘了点一下赞哦
ES6 class
class Chameleon{
static colorChange (newColor){//flag1
this.newColor = newColor
console.log(this.newColor)
return this.newColor
}
constructor({newColor = 'green'} = {}){
this.newColor = newColor
}
}
const data = new Chameleon({
newColor:"red"
})
Chameleon.colorChange("yellow")//"yellow"
data.colorChange("orange") //TypeError
这题的主要问题是
为什么调用类实例data中原型上的方法报错?
flag1处:方法前加上了关键字 static,表示该方法为静态方法
其实这个方法就不在原型上了,而是在类上,所以不能被实例所继承,而是直接通过类来调用
console.log(Chameleon.prototype.colorChange)//undefined
console.log(Chameleon.colorChange)//[Function: colorChange]