es6中的类

类是构造函数的语法糖
(1) es5构造函数

function Animal(name,age){
		this.name = name;
		this.age = age;
	}
	Animal.prototype.sayName = function(){
		console.log("my name is",this.name);
	}
	Animal.prototype.sayAge = function(){
		console.log("my age is",this.age);
	}
	
	//继承
	function Dog(name,age,gender){
		Animal.call(this,name,age)
		this.gender = gender;
	}
	Dog.prototype = new Animal();
	Dog.prototype.constructor = Dog;
	Dog.prototype.sayGender = function(){
		console.log("my gender is",this.gender);
	}
	let d = new Dog("一休",2,"male");
	d.sayName()
	d.sayGender();

(2) 语法
1、 类的声明

class 类名 {
	constructor(构造函数形式参数){
		this.xxx = xxx;
	}
	xxx(){
}  
	yyy(){
	}
}

this表示当前构造函数的实例对象

  1. 类的继承
class 子类名 extends 父类名 {
	constuctor(子构造函数形式参数){
		super(x,y)
		this.z = z;
	}
}

任意一个类如果你不提供构造函数,那么系统会为你自动分配一个构造函数,这个构造函数如下

constructor(a,b,c){
	super(a)
}

super 是借用构造函数的语法糖

(3) this
不管是构造函数还是普通方法,this都指向当前类的实例对象

es6的类

<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>es6 类</title>
	<script>
		// Animal类
		class Animal {
			//1. 构造方法
			constructor(name,age){
				this.name = name;
				this.age = age;
			}
			//2. 普通方法
			sayName(){
				console.log("我的名字叫",this.name);
			}
			sayAge(){
				console.log("我的年龄为",this.age)
			}
		}
		
		// 原型链继承
		class Dog extends Animal{
			constructor(name,age,gender){
				super(name,age);
				this.gender = gender;
			}
			sayGender(){
				console.log("我的性别",this.gender);
			}
		}

		let d = new Dog("一休",2,"male");
		console.log(d);
		d.sayName();
		d.sayGender();
	</script>
</head>
<body>
	
</body>
</html>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值