es6-class基本语法

class基本语法

es5创建对象的方式

function Point(x,y){
	this.x = x;
	this.y = y;
	this.line = function(){
		return "this is line"
	}
}
Point.prototype.toString = function(){
	return '(' + this.x + ',' + this.y + ')';
}
var p = new Point(1,2);
console.log(p)

原型属性(prototype属性)原型属性也叫prototype属性,每一个函数都有prototype属性,初始指向一个空对象(也叫原型对象)。我们可以给prototype进行修改,让它引用一个费控对象,只有在该函数是构造函数时
才有实际意义。对于费构造函数,不会对函数的运行造成影响。当函数为构造函数时候,我们可以通过原型属性修改原型对象,达到给构造给用构造函数创建的对象增加属性和行为的功能

上面代码中我们创建了一个名为Point的构造函数,并且在其原型上添加了toString方法返回一个点坐标的字符串

浏览器控制台结果

ES6引用了Class(类)这个概念,作为对象模板。通过lass关键字,可以定义类

基本上,ES6的class可以看作是一个语法糖,他的绝大部分功能,ES5都可以做到,新的class写法只是让对象原型的写法更加清晰、更像面向对象变成的语法而已。上面的代码用ES6的class改写,如下所示

class Point{
	constructor(x,y){
		this.x = x ;
		this.y = y ;
		console.log(this)
	}
	toString(){
		return '('+ this.x + ', ' + this.y + ')';
	}
}
console.log(new Point(1,2))

上面代码定义了一个类,可以看到里面有一个constructor方法,这就是构造方法,而this关键字则代表实例对象。也就是说ES5的构造函数Point,对应ES6的Point类的构造方法

Point类除了构造方法,还定义了一个toString方法。注意,定义"类"的方法的时候,前面不需要加上function这个关键字,直接把函数定义放进去了就可以了。另外,方法之间不需要逗号分隔,加了会报错

浏览器控制台结果

通过es5和es6创建对象的结果,我们可以看出es5可以在构造函数的原型prototype上定义方法,而es6中定义的方法就是直接在类Point的原型prototype上的

ES6的类,完全可以看作构造函数的另一种写法

	class Point{
		//...
	}
	console.log(typeof Point);//function
	console.log(Point === Point.prototype.constructor);//true

上面代码表明,类的数据类型就是函数,类本身就指向构造函数
使用的时候,也是直接对类使用new命令,跟构造函数的用法完全一致

class Bar{
	doStuff(){
		console.log('stuff')
	}
}
var b = new Bar();
b.doStuff();
console.log(b)

构造函数的prototype属性,在ES6的"类"上面继续存在。事实上,类的所有方法都定义在类的prototype属性上面。

class Point{
	constructor(){}
	toString(){}
	toValue(){}
}
//等同于
Point.prototype = {
	constructor(){},
	toString(){},
	toValue(){}
}

在类的实例上面调用方法,其实就是调用原型上的方法

class B {};
let b = new B();
b.constructor === B.prototype.constructor //true

上面的代码中,b是B类的实例,它的constructor方法就是B类原型的constructor方法

由于类的方法都定义在prototype对象上面,所以类的新方法可以添加在prototype对象上面。Object.assign方法可以很方便地一次向类添加多个方法

class Point{
	constructor(){
		
	}
}
Object.assign(Point.prototype,{
	toString(){},
	toValue(){}
})

console.log(new Point())

prototype对象的constructor属性,直接指向'类'的本身,这与ES5的行为是一致的。

Point.prototype.constructor === Point //true

另外,类的内部所有定义的方法,都是不可枚举的(non-enumerable)

枚举:在JavaScript中,对象的属性分为可枚举和不可枚举之分,它们是由属性的enumerable值决定的。可枚举性决定了这个属性是否能被for...in查找遍历到,除此之外,还有Object.keys方法和JSON.stringify

class Point{
	constructor(x,y){
		//
	}
	toString(){
		
	}
}
console.log(Object.keys(Point.prototype))//[]
console.log(Object.getOwnPropertyNames(Point.prototype))

上面的代码中,toString方法是Point类内部定义的方法,它是不可枚举的。这一点与ES5的行为不一致。

es5

function Point(x,y){
	this.x = x;
	this.y = y;
	this.line = function(){
		console.log("this line is x,y")
	}
}
Point.prototype.toString = function(){
	return '(' + this.x + ',' + this.y + ')';
}
var p = new Point(1,2);
console.log(Object.keys(Point.prototype))//[]
console.log(Object.getOwnPropertyNames(Point.prototype))

由结果我们可以知道,采用ES5的写法,toString方法就是可枚举的

constructor方法

constructor方法是类的默认方法,通过new命令生成对象实例时,自动调用该方法。一个类必须有constructor方法,如果没有显示定义,一个空的constructor方法会被默认添加。

class Point{
}
//等同于
class Point{
	constructor(){}
}

上面代码中,定义了一个空的类Point,Javscript引擎会自动为它添加一个空的constructor方法

constructor方法默认返回实例对象(即this),完全可以指定返回另一个对象

class Foo{
	constructor(){
		
	}
}
console.log(new Foo() instanceof Foo)//true
class Foo1{
	constructor(){
		return Object.create(null)
	}
}
console.log(new Foo1())//{}
console.log(new Foo1() instanceof Foo1)//false

上面代码中,constructor函数返回一个全新的对象,结果导致实例对象不是Foo1类的实例

类必须使用new调用,否则会报错。这是它跟普通构造函数的一个主要区别,后者不用new也可以执行

class Foo{
	constructor(){
		return Object.create(null)
	}
}
Foo()
//TypeError:Class constructor Foo cannot be invoked without 'new'

类的实例

生成的实例的写法,与ES5完全一样,也是使用new命令。前面说过,如果忘记加上new,象函数那样调用类,将会报错

class Point{
	
}
//报错
var point = Point(2,3);
//正确
var point = new Point(2,3);

与ES5一样,实例的属性除非显示定义在其本身(即定义在this对象上),否则都是定义在原型上(即定义在class上)

class Point{
	constructor(x,y){
		this.x = x ;
		this.y = y ;
	}
	toString(){
		return '('+this.x + ',' + this.y + ')';
	}
}

var point = new Point(2,3);
console.log(point.toString());
console.log(point.hasOwnProperty('x'));
console.log(point.hasOwnProperty('y'));
console.log(point.hasOwnProperty('toString'));
console.log(point.__proto__.hasOwnProperty('toString'));

上面代码中,x和y都是实例对象point自身的属性(因为定义在this变量),所以hasOwnProperty方法返回true,而toString是原型对象的属性(因为定义在Point类上),所以hasOwnProperty方法
返回false。这些都与ES5的行为保持一致

与ES5一样,类的所有实例共享一个原型对象

var p1 = new Point(2,3);
var p2 = nwe Point(3,2);
p1.__proto__ === p2.__proto__//true

上面代码中,p1和p2都是Point的实例,他们的原型都是Point.prototype,所以__proto__属性是相等的
这也意味着,可以通过实例的__proto__属性为"类"添加方法

__proto__并不是语言本身的特性,这是各大厂商具体实现时添加的私有属性,虽然目前很多现代浏览器js引擎中都提供了这个私有
属性,但依旧不建议在生产中使用该属性,避免对环境产生依赖。生产环境中,我们可以使用Object.getPrototypeOf方法来获取实例对象的原型,
然后在来为原型添加方法/属性

function Point(x,y){
	this.x = x;
	this.y = y;
	this.line = function(){
		console.log("this line is x,y")
	}
}
Point.prototype.toString = function(){
	return '(' + this.x + ',' + this.y + ')';
}
var p = new Point(1,2);
let p1 = new Point(2,3);
let proto = Object.getPrototypeOf(p);
proto.toValue = function(){
	return "value"
}
console.log(p,p1)

上面代码中,我们可以看出使用Object.getPrototypeOf以后,在得到的原型上添加方法toValue,随后,我们在创建实例p1,p1原型上也存在toValue方法,说明了实例对象的原型是共用的

取值函数和存值函数

与ES5一样,在"类"的内部可以使用getset关键字,对某个属性设置存值函数和取值函数,拦截该属性的存取行为

class MyClass{
	constructor(){
		
	}
	get prop(){
		return 'getter'
	}
	set prop(value){
		console.log('setter:' + value)
	}
}

let inst = new MyClass();
inst.prop = 123;
console.log(inst)
console.log(inst.prop)

上面代码中,prop属性有对应的村值函数和取值函数,因此赋值和读取行为都被自定义了。

存值函数和取值函数是设置在属性的Descriptor对象上的

class CustomHTMLElement {
  constructor(element) {
this.element = element;
  }

  get html() {
return this.element.innerHTML;
  }

  set html(value) {
this.element.innerHTML = value;
  }
}

var descriptor = Object.getOwnPropertyDescriptor(
  CustomHTMLElement.prototype, "html"
);

"get" in descriptor  // true
"set" in descriptor  // true

上面代码中,存值函数和取值函数是定义在html属性的描述对象上面,这与ES5完全一致

属性表达式

let methodName = 'getArea';
class Square{
	constructor(length){
		this.length = length;
	}
	[methodName](){
		return this.length*this.length
	}
}
let s = new Square(4)
console.log(s[methodName]())//16

上面代码中,Square类的方法名可以用表达式表示

class表达式

与函数一样,类也可以使用表达式的形式定义

const MyClass = class Me{
	getClassName(){
		return Me.name
	}
}

let inst = new MyClass();
console.log(inst.getClassName());//Me
console.log(me.getClassName());//Uncaught ReferenceError: me is not defined

上面代码使用表达式表达了一个类。需要注意的是,这个类的名字是Me,但是Me只是在Class的内部可用,只带当前的类。在Class外部,这个类只能用 MyClass引用,如果在
外部引用的话,将会报错。如果类的内部没有用到的话,可以省略Me,也就是可以写成下面的形式

const MyClass = class {
}

采用Class表达式,可以写出立即执行的class

let person = new class {
	constructor(name){
		this.name = name
	}
	sayName(){
		console.log(this.name)
	}
}("张三")
person.sayName()//张三

注意点

  1. 严格模式
    类和模块的内部,默认就是严格模式,所以不需要使用use strict指定运行模式。只要你的代码写在类或模块中,就只有严格模式可用。考虑到未来所有的代码,其实都是
    运行在模块之中,所以ES6世纪上把整个语言升级到了严格模式。

  2. 不存在提升
    类不存在变量提升,这一点与ES5完全不同。

new Foo();//ReferenceError
class Foo{}

上面代码中,Foo类使用在前,定义在后,这样会报错,因为ES6不会把类的生命提升到代码头部。这种规定的原因与下文要提到的继承有关,必须保证子类在父类之后定义。

{
	let Foo = class{};
	class Bar extends Foo {}
}

上面代码不会报错,因为Bar继承Foo的时候,Foo已经有定义了。但是,如果存在class的提升,上面代码就会报错,因为class会被提升到代码头部,而let命令是不提升的,所以导致Bar继承Foo
的时候,Foo还没有定义。

  1. name属性
    由于本质上,ES6的类知识ES5构造函数的一层包装,所以函数的许多特性都被class继承,包括name属性
class Point{
	
}
console.log(Point.name)//Point

name属性总是返回紧跟在class关键字后面的类名

  1. Generator方法
    如果某个方法之前加上(*),就表示该方法是一个Generator函数。
class Foo{
	constructor(...args){
		this.args = args
	}
	* [Symbol.iterator](){
		console.log(Symbol.iterator)
		for(let arg of this.args){
			yield arg
		}
	}
}
for (let x of new Foo('hello','world')) {
	console.log(x)
}

上面代码中,Foo类的Symbol.iterator方法前有一个星号,表示该方法是一个Generator函数。Symbol.iterator方法返回一个Foo类的默认遍历器。for...of循环
会自动调用这个遍历器

  1. this指向
    类的方法内部如果含有this,它默认指向类的实例。但是,必须非常小小,一旦单独使用该方法,很可能报错
class Logger{
	printName(name = 'there'){
		console.log(this)
		this.print(`hello ${name}`)
	}
	print(text){
		console.log(text)
	}
}
const logger =  new Logger();
const {printName} = logger;
console.log(printName);
printName()

上面代码中,printName方法中的this,默认指向Logger类的实例。但是,如果将这个方法提取出来单独使用,this会指向该方法运行时候所在的环境(由于class内部
是严格模式,所以this实际指向的是undefined),从而导致找不到print方法而报错。

一个比较简单的解决方法是,在构造方法中绑定this,这样就不会找不到printf方法了

class Logger{
	constructor(){
		this.printName = this.printName.bind(this)
	}
	printName(name = "there"){
		console.log(this)
		this.printf(`hello ${name}`)
	}
	printf(text){
		console.log(text)
	}
	
}
const logger = new Logger();
const {printName} = logger;
console.log(printName);

printName()

另一种方法是使用箭头函数

class Obj {
	constructor(){
		this.getThis = () => this;
	}
}
const myObj = new Obj();
console.log(myObj.getThis() === myObj)//true

箭头函数内部的this总是指向定义时候所在的对象。上面代码中,箭头函数位于构造函数内部,他的定义生效的时候,是在构造函数执行的时候。这时,箭头函数所在的运行环境,肯定是
实例对象,所以this会总是指向实例对象

还有一种解决方法是使用Proxy,获取方法的时候,自动绑定this

class Logger{
	constructor(){
		this.printName = this.printName.bind(this)
	}
	printName(name = "there"){
		console.log(this)
		this.printf(`hello ${name}`)
	}
	printf(text){
		console.log(text)
	}
	
}
function selfish(target){
	const cache = new WeakMap();
	const handler = {
		get(target,key){
			const value = Reflect.get(target,key);
			if(typeof value !== 'function'){
				return value
			}
			if(!cache.has(value)){
				cache.set(value,value.bind(target));
			}
			return cache.get(value);
		}
	};
	const proxy = new Proxy(target,handler);
	return proxy;
}

const logger = selfish(new Logger);
const {printName} = logger;
console.log(printName);
printName()

静态方法

类相当于实例的原型,所有在类中定义的方法,都会被 实例继承。如果在一个方法前加上static关键字,就表示该方法不会被实例继承,而是直接通过类来调用,这就称为"静态方法"

class Foo {
	static classMethod(){
		return 'hello'
	}
}
console.log(Foo.classMethod())//hello
var foo = new Foo()
console.log(foo)
foo.classMethod( )//Uncaught TypeError: foo.classMethod is not a function

上面代码中,Foo类的classMethod方法前有static关键字,表明该方法是一个静态方法,可以直接在Foo类上调用(Foo.classMethod()),而不是在Foo类的实例上
调用,如果在实力上调用静态方法,会跑出一个错误,表示不存在该方法

注意,如果静态方法包含this关键字,这个this指的是类,而不是实例

class Foo{
	static bar(){
		this.baz();
	}
	static baz(){
		console.log('hello');
	}
	baz(){
		console.log('world');
	}
}
Foo.bar()//hello

上面代码中,静态方法bar调用了this.baz,这里的this指的是Foo类,而不是Foo的实例,等同于调用了Foo.baz。另外,从这个例子还可以看出,静态方法可以与费静态方法重名

父类的静态方法,可以被自雷继承。

class Foo{
	static classMethod(){

		return 'hello'
	}
}
class Bar extends Foo{
	
}
console.log(Bar.classMethod())// hello

上面代码中,父类Foo有一个静态方法,子类Bar可以调用这个方法

静态方法也是可以从super对象上调用的

class Foo{
	static classMethod(){
		return 'hello';
	}
}
class Bar extends Foo{
	static classMethod(){
		return super.classMethod() + ',too'
	}
}
console.log(Bar.classMethod())//hello,too

实例属性的新写法

实例属性除了定义在constructor()方法里的this上面,也可以定义在类的最顶层

class IncreasingCounter{
	constructor(){
		this._count = 0;
	}
	get value(){
		console.log('getting the current value');
		return this._count;
	}
	increment(){
		this._count++;
	}
}
let increasingCounter = new IncreasingCounter();
increasingCounter.increment()
console.log(increasingCounter)

上面代码中,实例属性this._count定义在constructor()方法里面。另一种写法是,这个属性也可以定义在类的最顶层,其他都不变

class IncreasingCounter{
	_count = 0;
	get value(){
		console.log('getting the current value');
		return this._count;
	}
	increament(){
		this._count++
	}
}
let increasingCounter = new IncreasingCounter();
increasingCounter.increament();
console.log(increasingCounter);		

在上面代码中,实例属性_count与取值函数 value()increment()方法。处于同一个层级。这时,不需要在实例属性前面加上this.

这种新写法的好处是,所有实例对象自身的属性都定义在类的头部,看上去比较整齐,一眼就能看出这个类有哪些实例属性

class foo{
	bar = 'hello';
	baz = 'world';
	constructor(){
	//
	}
}

上面的代码,一眼就能看出foo类有两个实例属性,一目了然。另外,写起来也比较简洁

静态属性

静态属性指的是Class本身的属性,即class.propName,而不是定义值私立对象this上的属性

class Foo{
	
}
Foo.prop = 1;
console.log(Foo.prop)//1

上面的写法为Foo类定义了一个静态属性prop

目前只有这种写法可行,因为ES6明确规定,class内部只有静态方法,没有静态属性。现在有一个天提供了类的静态属性,写法是在实例属性的前面,加上static关键字

class MyClass{
	static myStaticProp = 42;
	constructor(){
		console.log(MyClass.myStaticProp);
	}
}
let myClass = new MyClass();
console.log(myClass)

这个新写法大大方便了静态属性的表达。

//old
class Foo{}
Foo.prop = 1
//new
class Foo{
	static prop=1
}

上面代码中,老写法的静态属性定义在类的外部。整个类生成以后,在生成静态属性,这样让人很容易忽略这个静态属性,也不符合相关代码应该放在一起的代码组织原则。另外,新写法是
显示原则。另外,新写法是显示声明,而不是赋值处理,语义更好

私有方法和属性


现有的解决方案

私有方法和私有属性,是只能在类的内部访问的方法和属性,外部不能访问。这是常见需求,有利于代码的封装,但ES6不提供,只能通过变通方法模拟实现。

class Widget{
	//共有方法
	foo(baz){
		this._bar(baz)
	}
	//私有方法
	_bar(baz){
		return this.snaf = baz
	}
}
console.log(new Widget())

上面代码中,_bar方法前面的下划线,表示这是一个只限于内部使用的私有方法。但是。这种命名是不保险的,在类的外部,还是可以调用到这个方法。

另一种方法就是索性将私有方法移除模块,因为模块内部的所有方法都是对外可见的

class Widget{
	foo(baz){
		bar.call(this,baz);
	}
}
function bar(baz){
return this.snaf = baz;
}

上面代码中,foo是公开方法,内部调用了bar.call(this,baz)。这使得bar实际上成为了当前模块的私有方法

还有一种方法是利用Symbol值的唯一性,将私有方法的名字命名为一个Symbol

const bar = Symbol('bar');
const snaf = Symbol('snaf');
export default class myClass{
	
  // 公有方法
  foo(baz) {
    this[bar](baz);
  }

  // 私有方法
  [bar](baz) {
    return this[snaf] = baz;
  }
}

上面代码中,bar和snaf都是Symbol值,一般情况下无法获取到他们,因此达到了私有方法和私有属性的效果。但是也不是绝对不行,Reflect.ownKeys()依然可以拿到他们

私有属性天

目前有一个天,Wieclass加了私有属性。方法是在属性名之前,使用#表示

class IncreasingCounter {
  #count = 0;
  get value() {
    console.log('Getting the current value!');
    return this.#count;
  }
  increment() {
    this.#count++;
  }
}

上面代码中,#count就是私有属性,只能在类的内部使用(this.#count)。如果在类的外部使用,就会报错

const counter = new IncreasingCounter();
counter.#count // 报错
counter.#count = 42 // 报错

上面代码在类的外部,读取私有属性,就会报错

下面是另一个例子。

class Point {
  #x;

  constructor(x = 0) {
    this.#x = +x;
  }

  get x() {
    return this.#x;
  }

  set x(value) {
    this.#x = +value;
  }
}

上面代码中,#x就是私有属性,在Point类之外是读取不到这个属性的。由于井号#是属性的一部分,使用时候必须带有#一起使用,所以#x和x是两个不同的属性

之所以要引入一个新的前缀#表示私有属性,而没有采用private关键字,是因为JavaScript是一门动态语言,没有类型声明,使用独立的符号视乎是唯一的比较方便可靠的方法,能够
准确地区分一种属性是否为私有苏醒。另外Ruby语言使用@表示私有属性,ES6没有用这个符号而使用#,是因为#已经被留给了Decorator

这种写法不进可以写私有属性,还可以用来写私有方法

class Foo {
  #a;
  #b;
  constructor(a, b) {
    this.#a = a;
    this.#b = b;
  }
  #sum() {
    return #a + #b;
  }
  printSum() {
    console.log(this.#sum());
  }
}

上面代码中,#sum()就是一个私有方法。另外,私有属性也可以设置getter和setter方法

class Counter {
  #xValue = 0;

  constructor() {
    super();
    // ...
  }

  get #x() { return #xValue; }
  set #x(value) {
    this.#xValue = value;
  }
}

上面代码中,#x是一个私有属性,它的读写都通过get #x()和set #x()来完成。
私有属性不限于从this引用,只要是在类的内部,实例也可以引用私有属性。

class Foo {
  #privateValue = 42;
  static getPrivateValue(foo) {
    return foo.#privateValue;
  }
}

Foo.getPrivateValue(new Foo()); // 42

上面代码允许从实例foo上面引用私有属性。私有属性和私有方法前面,也可以加上static关键字,表示这是一个静态的私有属性或私有方法。

class FakeMath {
  static PI = 22 / 7;
  static #totallyRandomNumber = 4;

  static #computeRandomNumber() {
    return FakeMath.#totallyRandomNumber;
  }

  static random() {
    console.log('I heard you like random numbers…')
    return FakeMath.#computeRandomNumber();
  }
}

FakeMath.PI // 3.142857142857143
FakeMath.random()
// I heard you like random numbers…
// 4
FakeMath.#totallyRandomNumber // 报错
FakeMath.#computeRandomNumber() // 报错

上面代码中,#totallyRandomNumber是私有属性,#computeRandomNumber()是私有方法,只能在FakeMath这个类的内部调用,外部调用就会报错。

new.target属性

new是从构造函数生成实例对象的命令。ES6为new命令引入了一个new.target属性,该属性一般用在构造函数之中,返回new作用域的那个构造函数。如果构造函数不是
通过new命令或Reflect.construct()调用的,new.target会返回undefined,因此这个属性可以用来确定构造函数是怎么调用的

function Person(name) {
  if (new.target !== undefined) {
    this.name = name;
  } else {
    throw new Error('必须使用 new 命令生成实例');
  }
}

// 另一种写法
function Person(name) {
  if (new.target === Person) {
    this.name = name;
  } else {
    throw new Error('必须使用 new 命令生成实例');
  }
}

var person = new Person('张三'); // 正确
var notAPerson = Person.call(person, '张三');  // 报错

上面代码确保构造函数只能通过new命令调用。Class 内部调用new.target,返回当前 Class。

class Rectangle {
  constructor(length, width) {
    console.log(new.target === Rectangle);
    this.length = length;
    this.width = width;
  }
}

var obj = new Rectangle(3, 4); // 输出 true

需要注意的是,子类继承父类时,new.target会返回子类。

class Rectangle {
  constructor(length, width) {
    console.log(new.target === Rectangle);
    // ...
  }
}

class Square extends Rectangle {
  constructor(length) {
    super(length, width);
  }
}

var obj = new Square(3); // 输出 false

上面代码中,new.target会返回子类。

利用这个特点,可以写出不能独立使用、必须继承后才能使用的类。

class Shape {
  constructor() {
    if (new.target === Shape) {
      throw new Error('本类不能实例化');
    }
  }
}

class Rectangle extends Shape {
  constructor(length, width) {
    super();
    // ...
  }
}

var x = new Shape();  // 报错
var y = new Rectangle(3, 4);  // 正确

上面代码中,Shape类不能被实例化,只能用于继承。

注意,在函数外部,使用new.target会报错。

原文地址:https://www.cnblogs.com/dehenliu/p/12523399.html