es6的class关键字与es5的构造函数

todo

构造函数:

function Point(x, y) {
  this.x = x;
  this.y = y;
}

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

var p = new Point(1, 2);

console.log(p)
console.log(p.toString)

效果等同于

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

var p = new Point(1, 2);

console.log(p)
console.log(p.toString)

但是意义不一样,前者定义在生成对象的原型链中;
后者直接定义在属性中

结果:

可见:

1、构造函数也是一个普通函数,创建方式和普通函数一样,但构造函数习惯上首字母大写

2、构造函数和普通函数的区别在于:调用方式不一样。作用也不一样(构造函数用来新建实例对象)

3、调用方式不一样。
    a. 普通函数的调用方式:直接调用 person();
    b.构造函数的调用方式:需要使用new关键字来调用 new Person();

4、构造函数的函数名与类名相同:Person( ) 这个构造函数,Person 既是函数名,也是这个对象的类名

5、内部用this 来构造属性和方法 

class:

ES6 的class可以看作只是一个语法糖,它的绝大部分功能,ES5 都可以做到,新的class写法只是让对象原型的写法更加清晰、更像面向对象编程的语法而已。上面的代码用 ES6 的class改写,就是下面这样。

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

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

猜你喜欢

转载自www.cnblogs.com/wangtong111/p/11326412.html