ES6,16、class

本文介绍了ES6中class的使用,包括构造函数、原型方法、静态属性和静态方法,并通过示例展示了如何创建和使用。同时,讲解了class的继承机制,通过extend关键字实现子类对父类的继承。class本质上是function的语法糖,提供了更简洁的面向对象编程语法。
摘要由CSDN通过智能技术生成

以前我们使用构造函数生成对象,这么做

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
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值