ES6中的class

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中的静态方法
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值