【JavaScript】Class类

ES6

ES6提供了更接近传统语言的写法,引入了Class(类)这个概念,作为对象的模板。通过class关键字,可以定义类。

定义类

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

  toString() {
    
    
    return '(' + this.x + ', ' + this.y + ')';
  }
}
  • 上面代码定义了一个“类”,可以看到里面有一个constructor方法,这就是构造方法,而this关键字则代表实例对象。也就是说,ES5的构造函数Point,对应ES6的Point类的构造方法。
  • 定义“类”的方法的时候,前面不需要加上function这个关键字,直接把函数定义放进去了就可以了。另外,方法之间不需要逗号分隔,加了会报错。

和ES5比较

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

  toString(){
    
    
    // ...
  }

  toValue(){
    
    
    // ...
  }
}

// 等同于

Point.prototype = {
    
    
  toString(){
    
    },
  toValue(){
    
    }
};
  • 类的内部所有定义的方法,都是不可枚举的(non-enumerable)。这一点与ES5的行为不一致。

Object.assign添加多个方法

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

Object.assign(Point.prototype, {
    
    
  toString(){
    
    },
  toValue(){
    
    }
});

类的属性名可以用表达式

let methodName = "getArea";
class Square{
    
    
  constructor(length) {
    
    
    // ...
  }

  [methodName]() {
    
    
    // ...
  }
}
  • 上面代码中,Square类的方法名getArea,是从表达式得到的。
  • constructor方法是类的默认方法,通过new命令生成对象实例时,自动调用该方法。一个类必须有constructor方法,如果没有显式定义,一个空的constructor方法会被默认添加。constructor方法默认返回实例对象(即this),完全可以指定返回另外一个对象。
  • 类的构造函数,不使用new是没法调用的,会报错。

通过__proto__属性添加方法

var p1 = new Point(2,3);
var p2 = new Point(3,2);

p1.__proto__.printName = function () {
    
     return 'Oops' };

p1.printName() // "Oops"
p2.printName() // "Oops"

var p3 = new Point(4,2);
p3.printName() // "Oops"
  • 使用实例的__proto__属性改写原型,必须相当谨慎,不推荐使用,因为这会改变Class的原始定义,影响到所有实例。
  • Class不存在变量提升(hoist)。

猜你喜欢

转载自blog.csdn.net/weixin_43698328/article/details/114217116
今日推荐