ES6 class 学习笔记

//传统ES5 class写法
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.toString())

// ES6写法
class Point {
    constructor(x, y) {
        this.x = x;
        this.y = y;
    }
    toString() { //不用写function 直接写名字就可以
        return '(' + this.x + ', ' + this.y + ')';
    }
    sayHello() {
        console.log('hello')
    }
}
//上面的代码等同于
Point.prototype = {
    constructor() { },
    toString() { },
    sayHello() { },
}
var p = new Point(1, 2) //写给Point的参数会给到constructor
console.log(p.toString())
p.sayHello()

// es5可以获取到point类内部的方法,
var Point = function (x, y) { }
Point.prototype.toString = function () {
    console.log('tostring fangfa1')
}
console.log(Object.keys(Point.prototype))

//es6不可获取
class Point {
    constructor(x, y) {
        this.x = x, this.y = y
    }
    toString() {
        console.log('tostring fangfa1')
    }
}

console.log(Object.prototype)
console.log(Object.getOwnPropertyNames(Point.prototype))

// 取值和复制 getter setter
class Myclass {
    get class() {
        return 'class:' + this.name
    }
    set class(name) {
        this.name = name
    }
}
var myclass = new Myclass()
myclass.class = 2034
console.log(myclass.class)


// 静态方法
// 加上static关键字,就表示该方法不会被实例继承,而是直接通过类来调用,
// 如果静态方法包含this关键字,这个this指的是类,而不是实例。
class Foo {
    static getFoo() {
        this.foo()
    }
    static foo() {
        console.log('hello foo')
    }
}
Foo.getFoo()

class bar extends Foo {
    // 父类的静态方法,可以被子类继承。
    static father() {
        return super.getFoo()
        //在子类中通过super调用
    }
}
bar.getFoo()
bar.father()

//静态属性
//原写法
class Foo {
}
Foo.prop = 1
console.log(Foo.prop)
//新写法
class bar {
    static myStaticProp = 42
}
console.log(bar.myStaticProp)
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值