前置内容javascript
class Point { constructor(x, y) { this.x = x this.y = y } toString() { return `(${this.x},${this.y})` } /* 静态方法 */ static hello() { console.log("hello world!") } } // 子类实例的构建,基于父类实例 // super 方法调用父类的实例。使用了super后,才能用this class ColorPoint extends Point { constructor(x, y, color) { super(x, y) // super做为方法,用在子类的构造,必须在this以前先调用 this.color = color } toString() { // super做为对象(对象调用方法),指向的是父类的原型对象即Point.prototype console.log(Point.prototype.toString === super.toString) // true return `color: ${this.color}, ${super.toString()}` } }
子类和父类是经过什么关键字实现继承?父类是Point,子类是ColorPoint如何写?java
经过extends关键字函数
class ColorPoint extends Point{ }
子类的属性和方法中,哪一个关键字是必须的?这个关键字怎么用?为何要这么用?this
super关键字必须。prototype
super关键字有两种用法,做为方法和做为对象。code
做为方法时,用在constructor方法中(用于子类的构造),必须在this以前调用。对象
做为对象时,用在其余方法中,调用父类的方法用。指向的是父类的原型对象。继承
Point.prototype.toString === super.toString // true /* super做为对象时,不能不调用方法,直接拿来用,好比 Point.prototype === super 就会控制台报错 */
ColorPoint.hello()
会输出什么?为何?会输出 hello world! 由于ColorPoint
是Point
的子类,会继承它的全部方法。hello()
是Point
的静态方法,也会被子类ColorPoint
继承。ip
如何从子类获取父类?代码演示get
Object.getPrototypeOf(ColorPoint) === Point //true
用Object.getPrototypeOf(childClass)
的方法能够判断一个类是否继承了另外一个类
super可做为方法,也可做为 对象
方法:子类的constructor中使用。
对象:在子类的其余方法中使用。普通方法 = > 指向父类原型对象(父类的方法所有定义在原型对象上); 静态方法 => 指向父类
子类的__proto__
属性,指向的是什么?
子类的__proto__
属性指向父类
colorPoint.__proto__ === Point // true // 构造函数的继承
子类的prototype属性的__proto__
属性指向什么?
子类的prototype属性的__proto__
属性指向父类的prototype属性
colorPoint.prototype.__proto__ === Point.prototype // true // 类的方法的继承
原生构造函数有哪些?简述下Boolean构造函数的用法.
Boolean Number String Array Date Function Regexp Error Object
Boolean() Boolean 对象是一个布尔值的对象包装器。当须要判断一个对象是正负时,能够这么作 将非布尔值转化为布尔值,用Boolean方法,Boolean(exp) 或者 !!(exp)
ES5是先新建子类的实例对象this,再将父类的属性添加到子类上。因为父类的内部属性没法获取,致使没法继承原生的构造 函数。
ES6 是先新建父类的实例对象this,而后再用子类的构造函数修饰 this,使得父类的全部行为均可以继承。