ES6语法学习(一):class(1)

JS中的类


先看一段代码

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

    toString(){
        return '('+this.x+','+this.y+')';
    }
}
var p = new Point(1,2);

学过了js中的原型链,现在又有了这种代码,所以说为什么还要学原型链。。。

学习原型链是有必要的,实际上js中的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);

第二块代码完全可以实现第一块代码的功能。那么问题来了,class Point是个什么类型呢?

class Point{
    //...
}

typeof Point // "function"
Point === Point.prototype.constructor //true

类的数据类型就是函数,类本身就指向构造函数。

再看一下类中的成员函数是如何实现的。

class Hello{
    constructor(){

    }
    toString(){

    }
    toValue(){

    }
    sayHello(){
        console.log("Hello");
    }
    sayGoodBye(){
        console.log("GoodBye");
    }
}
var hello = new Hello();
hello.sayHello();//"Hello"
hello.sayGoodBye();"GoodBye"

试想一下,直接用ES5写的话怎么实现?

没错,就是原型链继承。

function Hello(){}
Hello.prototype = {
    constructor(){

    },
    toString(){

    },
    toValue(){

    },
    sayHello(){
        console.log("Hello");
    },
    sayGoodBye(){
        console.log("GoodBye");
    }
}

实际没什么区别,只是更好的方便理解而已。

因为类中的方法都在prototype对象里,所以向类中添加方法就是再prototype里添加方法。

Object.assgin(Hello.prototype,{
    fun1(){},
    fun2(){}
})

此方法可以一次性向类中添加多个方法。并且可以动态添加方法,亲测。

这里写图片描述

今天就总结这么多吧。。Bye~

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值