类的定义与用法
注意几点:
(1)类的定义不会被提升,必须在访问前对其进行定义
(2)类不可以重复定义
(3)类里面的方法不需要function关键字,方法之间不需要加分号
先回忆一下ES5中的知识,ES5中构造函数的写法
<script>
// 构造函数
function Student(){
this.name = "汤姆";
this.age = 20;
}
Student.prototype.play = function(){
console.log("每天走一走,烦恼都没有");
}
var student = new Student();
console.log(student.name);
ES6中,类的概念 作为创建对象的模板,通过class关键字,来定义类
class Student{
constructor(name,val){//传入形参
this.name = name;
this.age = 20;
this.val = val;
//构造函数内部也可以声明方法
this.setData(val);
}
//类中声明方法
eat(){
console.log(`我叫${this.name}吃嘛嘛香`);//使用模版字符串取值
}
//存值
setData(value){
this.val = value;
// console.log(this.val);
}
//取值
getData(){
return this.val;
}
}
let student = new Student("唐老鸭","米老鼠");
console.log(student.name);
student.eat();
console.log(student.getData());
</script>