ES6类class

class类

es6中为了更加好的把js设计成面向对象的语言的语法特征

		new Person()
			 class Person{
				 constructor(){}
			 }
			 new Person()

1.类的语法
类名要大写

	class person{

			}
			var p1=new person()
			console.log(p1)

声明类

	class Person{				
			}
			let p1=new Person()
			console.log(p1)			

匿名类

		var fn=class{				
			}
			var f1=new fn()
			console.log(f1)

2、js没有类 是原型的思想设计的类,但是学习和使用这个技术时,心中要用类的思想学习

		class Person{
				// if(100){
				// 	console.log(1111)
				// }
				constructor(a,b,c){
					console.log(666666)

					this.x=a
					this.b=b
				}
				//对象的属性
				life=50
				//对象的原型对象的方法
				say1(){
					console.log(111,this.x)					
				}
				//类的静态属性
				static life=200
				//类的静态方法
				static say2(){
					console.log(222)					
				}
			}
			// console.log(typeof(Person))
			var p1=new Person(10,20,30)
			//Person类的内部可以写一个constructor方法 用这个类创建对象时 就会运行构造函数
			//不写构造函数 系统会默认有一个空的构造运行
			console.log(p1)
			// p1.say1()
			console.log(Person.life)
			console.log(Person.say2)

			

• constructor 方法是类的默认方法,创建类的对象时被调用,在实例对象的原型上。也被称为类的构造方法(构造函数、构造器)。一个类中有且仅有一个构造方法。
• 原型方法:不需要使用function关键字,通过“对象.原型方法”调用。
• 静态方法:使用static修饰,给类添加静态属性和方法,调用时不需要创建对象,直接通过“类名.静态方法”调用
3、类的继承

  • 解决代码的复用
  • 使用extends关键字实现继承
  • 子类可以继承父类中所有的方法和属性
  • 子类只能继承一个父类(单继承),一个父类可以有多个子类
  • 子类的构造方法中必须有super()来指定调用父类的构造方法,并且位于子类构造方法中的第一行
  • 子类中如果有与父类相同的方法和属性,将会优先使用子类的(覆盖)
class People {
    //父类构造方法
	constructor() {
        this.a = 100; //父类中定义的变量
		console.log("People constructor");
	}
    //原型方法
	eat() {
		console.log("eat...")
	}
    //静态方法
    static play() {
		console.log("play...")
	}
}
			
class Student extends People {
    //子类构造方法
	constructor() {
		super(); //调用父类构造器,必须存在,且位于子类构造器第一行的位置
        this.b = 200; //子类定义的变量
		console.log("Student constructor");
	}
	study() {
		console.log("study...");
	}
}
			
let stu = new Student();
console.log(stu.a, stu.b);
stu.eat();
stu.study();
Student.play();

内部类:属于外部类的成员,必须通过“外部类.内部类”访问

// 外部类
class Outer {
	constructor() {
         console.log("outer");
    }
}
// 内部类
Outer.Inner = class {
    constructor() {
         console.log("Inner");
    }
}     
new Outer.Inner();
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值