Class 的基本用法

新写法:所有实例对象自身的属性都定义在类的头部,看上去比较整齐,一眼就能看出这个类有哪些实例属性。另外,写起来也比较简洁。

class Form {
    // 设置默认值
    x = ''
    y = ''
    arr = []

    constructor() {
        // ...
    }
    
    // 对数据做输出处理
    formData() {
        return {
            x: this.x,
            y: this.y,
            string: this.arr.join(',') // "1, 2, 3"
        }
    }

    // 给实例赋值
    assignData(data) {
        if (!!data) {
            this.x = data.x
            this.y = data.y
            this.arr = data.string.split(',') // [1, 2, 3]
        }
    }

    // 其他方法
    toString() {
        return '(' + this.x + ', ' + this.y + ')';
    }
}

let form = new Form()
form.assignData({
    x: 'hello',
    y: 'world',
    string: '1,2,3,4,5,6'
})

结果: 


以下均摘自参考 :Class 的基本语法


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

  toString() {
    return '(' + this.x + ', ' + this.y + ')';
  }
}
class Point {
  constructor() {
    // ...
  }

  toString() {
    // ...
  }

  toValue() {
    // ...
  }
}

// 等同于

Point.prototype = {
  constructor() {},
  toString() {},
  toValue() {},
};

在类的实例上面调用方法,其实就是调用原型上的方法。
可复习一下原型链:

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

b.constructor === B.prototype.constructor // true

constructor 方法

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

class Point {
}

// 等同于
class Point {
  constructor() {}
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值