还在纠结怎么写class嘛
这篇文章只介绍ES6的新写法,各位同志,放弃es5,拥抱es6吧。
1、写法
class Myclass{
constructor(x, y) {
this.x = x;
this.y = y;
}
toString() {
return '(' + this.x + ', ' + this.y + ')';
}
}
var p = new Myclass(1, 2);
上面的声明一个类,并初始化了参数和一个toString方法,代码简洁。类必须使用new调用,否则会报错
constructor()方法代表构造函数,this关键字则代表实例对象。
2、解析
class Myclass{
// ...
}
typeof Myclass// "function"
Myclass=== Myclass.prototype.constructor // true
上面说明,Myclass数据类型是函数,类本身就指向构造函数。事实上,类的所有方法都定义在类的prototype属性上面,因此,在类的实例上面调用方法,其实就是调用原型上的方法。
class B {
toString() {
// ...
}
}
const b = new B();
b.toString === B.prototype.toString // true
b.constructor === B.prototype.constructor // true
1、constructor 方法
constructor()方法是类的默认方法,通过new命令生成对象实例时,自动调用该方法。一个类必须有constructor()方法,如果没有显式定义,一个空的constructor()方法会被默认添加。constructor()方法默认返回实例对象
class Myclass{
}
// 等同于
class Myclass{
constructor() {}
}
2、this 的指向
类的方法内部如果含有this,它默认指向类的实例。
class Obj {
constructor() {
this.getThis = () => this;
}
}
const myObj = new Obj();
myObj.getThis() === myObj // true
如果你对JS的this指向并不太理解的话建议使用箭头函数,就像上面那样。
如果静态方法包含this关键字,这个this指的是类,而不是实例。
如:
class Foo {
static bar() {
this.baz();
}
static baz() {
console.log('hello');
}
}
Foo.bar() // hello
3、属性定义
实例的属性除非显式定义在其本身(即定义在this对象上),否则都是定义在原型上(即定义在class上)。
//定义类
class Myclass{
constructor(x, y) {
this.x = x;
this.y = y;
}
toString() {
return '(' + this.x + ', ' + this.y + ')';
}
}
var point = new Myclass(2, 3);
point.toString() // (2, 3)
point.hasOwnProperty('x') // true
point.hasOwnProperty('y') // true
point.hasOwnProperty('toString') // false
point.__proto__.hasOwnProperty('toString') // true
上面代码中,x和y都是实例对象point自身的属性(因为定义在this对象上),所以hasOwnProperty()方法返回true,而toString()是原型对象的属性(因为定义在Point类上),所以hasOwnProperty()方法返回false。
3、用法
class Bar {
doStuff() {
console.log('stuff');
}
}
const b = new Bar();
b.doStuff() // "stuff"
使用的时候,也是直接对类使用new命令,跟构造函数的用法完全一致。
我们可以使用Object.assign()方法一次向类添加多个方法。
class Myclass{
constructor(){
// ...
}
}
Object.assign(Myclass.prototype, {
toString(){},
toValue(){}
});
4、静态方法
类相当于实例的原型,所有在类中定义的方法,都会被实例继承。如果在一个方法前,加上static关键字,就表示该方法不会被实例继承,而是直接通过类来调用,这就称为“静态方法”。
class Foo {
static classMethod() {
return 'hello';
}
}
Foo.classMethod() // 'hello'
var foo = new Foo();
foo.classMethod()
// TypeError: foo.classMethod is not a function
父类的静态方法,可以被子类继承。关于继承留单独做下一次单篇介绍。
5、get和set关键字
静态属性指的是 Class 本身的属性,即Class.propName,而不是定义在实例对象(this)上的属性。
在“类”的内部可以使用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'
其他的关键字比如super,还有如何继承,有机会再聊