20-ES6(3)class基本语法

Class基本语法


关于es6的class简介:

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

例子:

//ES5写法
function PointES5(x, y) {
  this.x = x;
  this.y = y;
}
PointES5.prototype.toString = function () {
  return 'ES5:(' + this.x + ', ' + this.y + ')';
};
var p = new PointES5(1, 2);

//定义类 ES6
class PointES6 {
  constructor(x, y) {
    this.x = x;
    this.y = y;
    this.say = function(){
      return "hello";
    }
  }
  toString() {
    return 'ES6:(' + this.x + ', ' + this.y + ')';
  }
}
var p2 = new PointES6(1, 2);
console.log(p2.hasOwnProperty('x')) // true
console.log(p2.hasOwnProperty('y')) // true
console.log(p2.hasOwnProperty('toString')) // false
console.log(p2.hasOwnProperty('say'))
console.log(p2.__proto__.hasOwnProperty('toString')) // true

es6 class中的constructor方法:

constructor方法是类的默认方法,通过new命令生成对象实例时,自动调用该方法。一个类必须有constructor方法,如果没有显式定义,一个空的constructor方法会被默认添加。
constructor方法默认返回实例对象(即this),完全可以指定返回另外一个对象。
例子:

class Foo {
  constructor(){
    return Object.create(null);
  }
}
new Foo() instanceof Foo // false

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

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

类的实例对象:

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

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

原文地址:https://www.cnblogs.com/fengxuefei/p/6250591.html