zoukankan      html  css  js  c++  java
  • Class

    class Point{
        constructor(){
    
        }
    
        toString(){
    
        }
    }
    
    console.log(Object.keys(Point.prototype))
    console.log(Object.getOwnPropertyNames(Point.prototype))

    上面就是一个类

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

    console.log(typeof Point)  // "function"
    console.log(Point ===Point.prototype.constructor)  // true

    2、构造函数的 prototype 属性在 ES6 的“类”上继续存在。事实上,类的所有方法都定义在类的 prototype 属性上。

    开头的代码等同于

    class Point{}
    Point.prototype = {
        constructor() {},
        toString() {},
    }

    由于类的方法(除 constructor 以外)都定义在 prototype 对象上,所以类的新方法可以添加在 prototype 对象上。 Object.assign 方法可以一次性的向类添加多个方法

    很重要的一点,类的内部定义的所有方法都是不可枚举的

    console.log(Object.keys(Point.prototype))  // []
    console.log(Object.getOwnPropertyNames(Point.prototype))  // ["constructor", "toString"]

    其中,Object.keys() 返回一个数组,包含对象自身所有可枚举属性,不包含 Symbol,Object.getOwnPropertyNames() 返回一个数组,包含自身所有属性,不包含 Symbol

    3、constructor方法

    constructor 方法是类的默认方法,通过 new 命令生成对象实例是自动调用该方法。一个类必须有 constructor 方法,如果没有定义,一个空的  constructor 方法会被默认添加。
    constructor 方法默认返回实例对象,也就是 this 的指向。不过完全可以指定返回另外一个对象
    4、继承
    class ColorPoint extends Point {
        constructor(x, y, color) {
            super(x, y) // 调用父类的 constructor(x, y)
            this.color = color
        }
    
        toString() {
            return this.color + '' + super.toString() // 调用父类的 toString()
        }
    }

    看到 extends 是不是很熟悉,用过 React 的人肯定知道,在 React 的 ES6 写法中我们经常这样写

    class XXXXX extends Component{}
    

    ColorPoint  通过 extends 可以继承 Point 类的所有属性和方法

    有没有留意到 constructor 和 toString方法中都出现了 super 关键字,他指代父类的实例。

    子类必须在 constructor 方法中调用 super 方法,否则新建实例就会报错。因为子类没有自己的 this 对象,而是继承了父类的 this 对象,如果不调用 super ,子类就得不到 this。

    其实 class 就是对对象原型的一种更加简洁的写法

  • 相关阅读:
    php system()和exec()差别
    linux目录中 /usr/local/bin 和 /usr/bin和/usr/local/etc
    mac rar命令相关
    php迭代器
    linux下的find文件查找命令与grep文件内容查找命令
    php 类中的静态属性
    mysql 语句执行顺序
    mysl
    MySQL中concat函数
    animation效果
  • 原文地址:https://www.cnblogs.com/lan1974/p/9443082.html
Copyright © 2011-2022 走看看