ES6 中的Class

栏目: JavaScript · 发布时间: 6年前

内容简介:ES5 的写法ES6 的写法在类的实例上面调用方法,其实就是调用原型上的方法。

基本用法

ES5 的写法

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);

ES6 的写法

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

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

在类的实例上面调用方法,其实就是调用原型上的方法。

class B {}
let b = new B();

b.__proto__.constructor === B.prototype.constructor?console.log("true"):console.log("false")
console.log(typeof b.__proto__.constructor)
console.log(typeof B.prototype.constructor)

ES6 中的Class

注:类的内部所有定义的方法,都是不可枚举的

constructor 方法

constructor方法是类的默认方法,通过new命令生成对象实例时,自动调用该方法。一个类必须有constructor方法,如果没有显式定义,一个空的constructor方法会被默认添加。

注意点

  • constructor方法默认返回实例对象(即this),完全可以指定返回另外一个对象。

    class Foo {
      constructor() {
        return Object.create(null);
      }
    }
    
    new Foo() instanceof Foo
    // false
  • 类必须使用new调用,否则会报错。

    class book{
        constructor(){
            this._year=2004;
            this.edition=1;
        }
        get year(){
            return this._year;
        }
        set year(newVal){
            if(newVal>2004){
                this._year=newVal;
                this.edition+=newVal-2004;
            }
        }
    }
    let b=new book();
    b.year = 2004; //2
    console.log(b.edition);

取值函数(getter)和存值函数(setter)

class book{
    constructor(){
        this._year=2004;
        this.edition=1;
    }
    get year(){
        return this._year;
    }
    set year(newVal){
        if(newVal>2004){
            this._year=newVal;
            this.edition+=newVal-2004;
        }
    }
}
let b=new book();
b.year = 2004; //2
console.log(b.edition);

ES6 中的Class


以上所述就是小编给大家介绍的《ES6 中的Class》,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对 码农网 的支持!

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

算法艺术与信息学竞赛

算法艺术与信息学竞赛

刘汝佳 / 清华大学出版社 / 2004-1 / 45.00元

《算法艺术与信息学竞赛》较为系统和全面地介绍了算法学最基本的知识。这些知识和技巧既是高等院校“算法与数据结构”课程的主要内容,也是国际青少年信息学奥林匹克(IOI)竞赛和ACM/ICPC国际大学生程序设计竞赛中所需要的。书中分析了相当数量的问题。 本书共3章。第1章介绍算法与数据结构;第2章介绍数学知识和方法;第3章介绍计算机几何。全书内容丰富,分析透彻,启发性强,既适合读者自学,也适合于课......一起来看看 《算法艺术与信息学竞赛》 这本书的介绍吧!

RGB转16进制工具
RGB转16进制工具

RGB HEX 互转工具

图片转BASE64编码
图片转BASE64编码

在线图片转Base64编码工具

RGB CMYK 转换工具
RGB CMYK 转换工具

RGB CMYK 互转工具