ES6中class类

2021-09-22  本文已影响0人  小溪流jun
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>

</body>
<script>
    /* 
        Es6中的class类
        ES6 的类,完全可以看作构造函数的另一种写法。
        class使用的时候,也是直接对类使用new命令,跟构造函数的用法完全一致。
        类的内部所有定义的方法,都是不可枚举的(non-enumerable)。
        constructor()方法是类的默认方法,通过new命令生成对象实例时,自动调用该方法
        类必须使用new调用,否则会报错。这是它跟普通构造函数的一个主要区别,后者不用new也可以执行
    
     */

    // 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("00000000", p)

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

    Object.assign(Point.prototype, {
        toNum() { },
        toValue() { }
    });
    let a = new Point(2, 3)
    //a是Point的实例
    console.log(a)
</script>

</html>
上一篇下一篇

猜你喜欢

热点阅读