以前我们使用构造函数生成对象,这么做
function Person(name) {
this.name = name
}
Person.prototype.sayName = function () {
console.log(this.name)
}
const kobe = new Person('科比')
kobe.sayName()//科比
而有ES6的class可以这么做
class Person {
constructor(name) {
//构造器
this.name = name
}
sayName() {
console.log(this.name)
}
}
const kobe = new Person('科比')
kobe.sayName()//科比
值得一提的是,class本质也是function,class是function的语法糖
class Person {}
console.log(typeof Person) // function
除了以上,还需要知道class的一下知识点静态属性,和静态方法,使用static定义的属性和方法只能class自己使用,实例用不了
class Person {
constructor(name) {
this.name = name
}
static age = 100
static fn() {
console.log('哈哈')
}
}
console.log(Person.age) //100
Person.fn()//哈哈
const sunshine_lin = new Person('大鱼');
console.log(sunshine_lin.age);//undefined
sunshine_lin.fn()//fn is not a function
extend 继承
class Animal {
constructor(name ,age) {
this.name = name;
this.age = age
}
}
class Cat extend Animal {
say() {
console.log(this.name,this.age)
}
}
const cat = new Cat('ketty0' , 6)//继承Animal的构造器
cat.say()// ketty 5