es5中的构造函数
function Person(name,age){
this.name = name
this.age = age
}
Person.prototype.say = function(){
console.log("say...")
}
var p1 = new Person("leo",18)
es6中的写法
class Person{
constructor(name.age){ //这里相当于是es5中的构造函数
this.name = name
this.age = age
}
say(){ //原型上的方法直接这样写
console.log("say...")
}
}
var p1 = new Person("leo",18)
p1.say()
- Person必须用new的形式调用
- class中函数和函数之间不需要以逗号隔开
- Person实际上还是一个函数 用typeof查看类型是function
静态方法
只能通过构造函数Person直接调用
class Person{
constructor(name.age){
this.name = name
this.age = age
}
static say(){ //静态方法前面需要加上关键字static
console.log("say...")
}
}
//调用
Person.say()
静态属性
class Person{
constructor(name.age){
this.name = name
this.age = age
}
}
//直接加载Person上
Person.hello = "world"
继承
class Person{
constructor(name,age){
this.name = name
this.age = age
}
say(){
console.log("我叫":this.name+"今年"+this.age+"岁")
}
static isHuman(obj){
return obj instanceof Person
}
}
// 创建一个coder属性和方法继承Person
class Coder extends Person{
constructor(name,age,money){
super(name,age)
this.money = momey
}
say(){
console.log("我叫":this.name+"今年"+this.age+"岁,"+"一个月赚"+this.money+"元")
}
}
var c1 = new Coder("leo",30,3000)
Coder.isHuman(1) //false
console.log(c1)
- 如果只是单纯的继承 constructor里面可以为空 但是必须写 否则会报错
- 在继承Person属性的前提下自己还要新添加一些属性需要写在constructor里面 并且必须调用super方法 相当于是把person中的属性调用过来
- coder可以直接调用person中的say方法 如果需要修改 直接在coder里面重写就可以了 重写say方法不会导致person中的say方法发生改变
- coder也可以直接调用person中的静态方法