Es6语法之Class

Class顾名思义,类。
其实JS也是一门面向对象的语言。
我们在JS中的实例化对象,如:
下面是ES5的写法:

function Fu(x,y){
this.x=x;
this.y=y;
}
var f=new Fu(2,3);
Fu.prototype.name=function(){
console.log(this.x,this.y)//2,3
}
f.name();

下面是ES6的写法:

   class Point {
      constructor(x, y) {
         this.x = x;
         this.y = y;
      }
      toString() {
         console.log(this.x,this.y)
      }

   }
   var point = new Point(2, 3);
   point.toString() // (2, 3)

到这里,可能大家就发现了什么。

class Fu {
  constructor() {
    // ...
  }

  toString() {
    // ...
  }

  toValue() {
    // ...
  }
}
// 等同于
Fu.prototype = {
  constructor() {},
  toString() {},
  toValue() {},
};

也就是

class F {}// 定义一个类。
let f= new F();// 实例化对象。
f.constructor === F.prototype.constructor //true

最后大家可能理解了,其实class类就是对构造函数的一次升级,让js更贴近我们所熟悉的面向对象。

猜你喜欢

转载自blog.csdn.net/qq_39045645/article/details/86689776