在ES6之前,我们是通过构造函数来定义类的
<script>
function Person(myName, myAge) {
this.name = myName;
this.age = myAge;
this.say = function() {
console.log("Hello World");
}
}
let p = new Person("Durant", 30);
console.log(p);
</script>
从ES6开始系统提供了一个名称叫做class的关键字, 这个关键字就是专门用于定义类的
<script>
class Person {
constructor(myName, myAge) {
this.name = myName;
this.age = myAge;
this.say = function() {
console.log("Hello World");
}
}
}
let p = new Person("Durant", 30);
console.log(p);
</script>
控制台输出:
如果想要给类的原型对象添加属性和方法,只可通过以下一种方式
<script>
class Person {
constructor(myName, myAge) {
this.name = myName;
this.age = myAge;
this.say = function() {
console.log("Hello World");
}
}
run() {
console.log("run"); //此时run方法是在原型对象中的
}
}
Person.prototype.type = '人';
Person.prototype.talk = function() { //添加方法也可以模仿run()方法那样实现
console.log("talk");
}
let p = new Person("Durant", 30);
console.log(p);
</script>
控制台输出:
在类中添加静态属性和静态方法:
<script>
class Person {
constructor(myName, myAge) {
this.name = myName;
this.age = myAge;
this.say = function() {
console.log("Hello World");
}
}
static talk() { //静态方法
console.log("123");
}
}
Person.num = 666; // 静态属性
let p = new Person("Durant", 30);
console.log(p);
</script>