class的基本用法(第一篇)——ES6篇

含义:

ES6提供了更接近传统与语言的写法,引入了class(类)这个概念,作为对象的模板。通过class关键字,可以定义类。它的绝大部分功能ES5都可以,只是让对象原型的写法更加清晰,更像面向对象编程的语法而已。

类的数据类型就是函数,类本身就指向构造函数

//定义类
class Point{
	constructor(x, y) {
		this.x = x;
		this.y = y;
	}

	toString() {
		return '(' + this.x + ',' + this.y + ')';
	}
}

用法:

使用的时候,也是直接对类使用new命令,跟构造函数的用法完全一致

  • 严格模式:类和模式的内部,默认的就是严格模式,所以不需要使用use strict指定
  • new关键字:类必须使用new调用,否则回报错
  • class表达式:与函数一样,类也可以使用表达式的形式定义
    • 与函数一样,类也可以使用表达式的形式定义
      const Myclass = class Me {
      	getClassName() {
      		return Me.name;
      	}
      };

      注意:上面代码表达式定义了一个类,这个类的名字是MyClass而不是Me

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

      let  person = new class {
      	constructor(name) {
      		this.name = name;
      	}
      
      	sayName() {
      		console.log(this.name);
      	}
      }('张三');
      
      person.sayName(); //‘张三’
  • 不存在变量提升: 类不存在变量提升,因为let命令是不提升的,否则在继承的时候容易报错
  • 私有方法和私有属性: 私有方法是常见需求,但ES6不提供,只能通过变通方法模拟实现

解决私有方法问题

方法一:

class Widget {
	//共有方法
	foo(baz) {
		this._bar(baz);
	}

	//私有方法
	_bar(baz) {
		return this.snaf = baz;
	}

	//....
}

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

方法二: 

将私有方法移出模块,因为模块内部的所有方法都是对外可以见的

class Widget {
	foo (baz) {
		bar.call(this, baz);
	}
	//...
}

function bar(baz) {
	return this.snf = baz;
}

内部调用了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值,导致第三方无法获取到它们,因此达到了私有方法和私有属性的效果。

this 的指向

类的方法内部如果含有this,它默认指向类的实例。但是,必须小心,一旦单独使用该方法,很有可能报错

class Logger{
	printName(name = 'there') {
		this.print(`hello ${name}`);
	}

	print(text) {
		console.log(text);
	}
}

const logger = new Logger();
const { printName } = logger;
printName();// TypeError: Cannot read property 'print' of undefined

解决方法一:

在构造方法中绑定this,这样就不会找不到print方法了。

class Logger{
	constructor() {
		this.printName = this.printName.bind(this);
	}
}

解决方法二:

使用箭头函数

class Logger {
	constructor() {
		this.printName = (name =  'there') => {
			this.print(`hello ${name}`);
		};
	}
	// ....
}

解决方法三:

使用proxy,获取方法的时候,自动绑定this

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, handle);
	return proxy;
}

const logger = selfish(new Logger());

 name 属性

ES6的类只是ES5的构造函数的一层包装,所以函数的许多特性都被class继承,包括name属性

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

class的取值函数(getter)和存值函数(setter)
与ES5一样,在“类”的内部可以使用get和set关键字,对某个属性设置存值函数和取值函数拦截该属性的存取行为

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

let inst = new MyClass();

inst.prop = 123;
//setter: 123

inst.prop
//'getter'

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

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.property, 'html'
);

class的Generator方法

如果某个方法加上星号(*),就表示该方法是一个Generator函数

class Foo {
	constructor(...arg) {
		this.args = args; 
	}
	* [Symbol.iterator]() {
		for (let arg of this.args) {
			yield arg;
		}
	}
}

for (let x of new Foo('hello', 'world')) {
	console.log(x);
}
// hello
// world

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

class 的静态方法

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

class Foo{
	static classMethod() {
		return 'hello';
	}
}

Foo.classMethod()	//'hello'

var foo = new Foo();
foo.classMethod()
// TypeError: foo.classMethod is not a function

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

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

Foo.bar() //hello

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

父类的静态方法,可以被子类继承

class Foo{
	static classMethod() {
		return 'hello';
	}
}

class Bar extends Foo{

}

Bar.classMethod();//'hello'

class Foo {
	static classMethod() {
		return 'hello';
	}
}

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

Bar.classMethod() 	//'hello, too'

class的静态属性和实例属性

静态属性指的是class本身的属性,即 class.propName,而不是定义在实例对象(this)上的属性

因为 ES6 明确规定,Class 内部只有静态方法,没有静态属性。
类的静态属性只要在上面的实例属性写法前面,加上static关键字就可以了。

new.target 属性

new是从构造函数生成实例对象的命令,ES6为new命令引入了一个 new.target属性,该属性一般用在构造函数之中,返回new命令作用于的那个
构造函数。如果构造函数不是通过new 命令调用的,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, '张三');

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, length)
	}
}

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

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

利用这个特点,可以写出不能独立使用,必须继承后才能使用的类
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);	//正确


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

 

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值