ES6中class的使用+继承

  • Post author:
  • Post category:其他



一.Class 介绍+基本语法


(1).介绍


通过class关键字,可以定义类。基本上,ES6 的class可以看作只是一个语法糖,它的绝大部分功能,ES5 都可以做到,新的class写法只是让对象原型的写法更加清晰、更像面向对象编程的语法而已。


(2).Class 的基本语法

//definedClasses.js

	//定义类
	class Person{  
		// 构造  
		constructor(x,y){  
			this.x = x;  
			this.y = y;  
		}  
	  
	   //定义在类中的方法不需要添加function
		toString(){  
			return (this.x + "的年龄是" +this.y+"岁");  
		}  
	}  
	export {
		Person
	};  
	
// test.vue
	<template>
		<div>
			<P id="testJs"></p>
		</div>
	</template>
	<script>
	import {Person} from '@/assets/js/definedClasses';  
	export default {   
		data() {
			return {
			}
		},
		mounted(){
			let text=document.getElementById("testJs");
			//使用new的方式得到一个实例对象
			let person = new Person('张三',12);  
			text.innerHTML=person.toString();//张三的年龄是12岁
			console.log(typeof  Person);//function  
		}
	}
	</script>


上面代码定义了一个“类”,可以看到里面有一个

constructor方法,这就是构造方法,而this关键字则代表实例对象

。也就是说,ES5的构造函数Person,对应ES6的Person类的构造方法。从console.log(typeof  Person);输出function ,看出

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




使用方式跟构造函数一样,对类使用new命令,跟构造函数的用法完全一致


let person = new Person(‘张三’,12);


person.toString();



构造函数的prototype属性,在ES6的“类”上面继续存在

。事实上,

类的所有方法都定义在类的prototype属性上面

,通过以下方式可是覆盖类中的方法,当然定义类的时候也可以通过这个方式添加方法。

class Person {
  constructor() {// ... }
 
  toString() {// ...}

  toValue() {// ...}
}

// 等同于

Person.prototype = {
	constructor() {},
	toString() {},
	toValue() {},
};

在类的实例上面调用方法,其实就是调用原型上的方法
console.log(person.constructor === Person.prototype.constructor);//true



Object.assign方法可以给对象Person动态的增加方法

,而Person.prototype = {}是覆盖对象的方法,或者在初始化的时候添加方法。

//test.vue
Object.assign(Person.prototype,{  
	getWidth(){  
		console.log('12');  
	},  
	getHeight(){  
		console.log('24');  
	}  
});  
console.log(Person.prototype);//就可以输出Person内所有方法 包括getWidth() getHeight()


补充:


Object.keys(obj),返回一个数组,数组里是该obj可被枚举的所有属性。Object.getOwnPropertyNames(obj),返回一个数组,数组里是该obj上所有的实例属性。

//ES5  
console.log(Object.keys(Person.prototype));//["toString", "getWidth", "getHeight"]  
console.log(Object.getOwnPropertyNames(Person.prototype));//["constructor", "toString", "getWidth", "getHeight"]  
  
//ES6  
console.log(Object.keys(Person.prototype));//["getWidth", "getHeight"]  
console.log(Object.getOwnPropertyNames(Person.prototype));//["constructor", "toString", "getWidth", "getHeight"]


(3).注意


①ES6类的constructor函数相当于ES5的构造函数

②通过class关键字,可以定义类

③类中定义方法时,前面不用加function,后面不得加  ,  ,方法全部都是定义在类的prototype属性中。

④类必须使用new调用,否则会报错

let person = new Person(‘张三’,12);

不能Person();

⑤ 类不存在变量提升,Foo类定义在前 使用在后,或者会报错

⑥name属性总是返回紧跟在class关键字后面的类名

class Point {}

Point.name // “Point”

⑦类的内部定义的所有方法都是不可枚举的

⑧类和模块内部默认采取严格模式

另外,下面这种写法是无效的。class内部只允许定义方法,不允许定义属性(包括静态属性)

class Foo{bar:2}




二.分析类class


1.constructor方法


是类的默认方法,通过new命令生成对象实例时,自动调用该方法。

一个类必须有constructor方法,如果没有显式定义,一个空的constructor方法会被默认添加


class Point {
}

// 等同于
class Point {
  constructor() {}
}


constructor方法默认返回实例对象(即this),完全可以指定返回另外一个对象.但是也可以指定constructor方法返回一个全新的对象,让返回的实例对象不是该类的实例。


2.类的实例对象


上面说了,不适用new实例会报错。


实例的属性除非显式定义在其本身(即定义在this对象上),否则都是定义在原型上(即定义在class上)。hasOwnProperty()函数用于指示一个对象自身(不包括原型链)是否具有指定名称的属性。如果有,返回true,否则返回false。

class Person{  
    // 构造  
    constructor(x,y){  
        this.x = x;  
        this.y = y;  
    }  
  
    toString(){  
        return (this.x + "的年龄是" +this.y+"岁");  
    }  
}  
  
let person = new Person('lis',8);  
console.log(person.toString());  
console.log(person.hasOwnProperty('x'));//true  
console.log(person.hasOwnProperty('y'));//true  
console.log(person.hasOwnProperty('toString'));//false  
console.log(person.__proto__.hasOwnProperty('toString'));//true


上面结果说明对象上有x,y属性,但是没有toString属性。也就是说x,y是定义在this对象上,toString定义在类上。

let person1 = new Person('张三',12);  
let person2 = new Person('李四',13);  
console.log(person1.__proto__ === person2.__proto__);//true



类的所有实例共享一个原型对象,person1和person2都是Person的实例,它们的原型都是Person.prototype,所以


__proto__属性


是相等的。这也意味着,可以

通过实例的__proto__属性为Class添加方法

。但是不建议使用,

因为这会改变Class的原始定义,影响到所有实例。





3.class表达式






类也可以使用表达式的形式定义。



const MyClass = class Me {
	getClassName() {
		return Me.name;
	}
};

let inst = new MyClass();
inst.getClassName() // Me
Me.name // ReferenceError: Me is not define


上面代码使用表达式定义了一个类。需要注意的是,

这个类的名字是MyClass而不是Me,Me只在 Class 的内部代码可用,指代当前类



如果类的内部没用到的话,可以省略Me,也就是可以写成下面的形式。


const MyClass = class { /* … */ };


三.私有方法和私有属性


(1).私有方法


1.一种做法是在命名上加以区别

// 私有方法

class Widget {



_bar(baz) {return this.snaf = baz;}

}

2.一种方法就是索性将私有方法移出模块,因为模块内部的所有方法都是对外可见的。

//PrivateMethod.js  
export default class PrivateMethod{  
  
    // 构造  
    constructor() {  
    }  
  
    getName(){  
        priName();  
    }  
}  
  
function priName(){  
    console.log('私有方法测试');  
}  
//test.vue  
import PriMe from './PrivateMethod';  
let prime = new PriMe();  
prime.getName();


3.利用Symbol值的唯一性,将私有方法的名字命名为一个Symbol值

const bar = Symbol('bar');
const snaf = Symbol('snaf');

export default class myClass{
  // 公有方法
  foo(baz) {
    this[bar](baz);
  }

  // 私有方法
  [bar](baz) {
    return this[snaf] = baz;
  }

  // ...
};


(2).私有属性


为class加了私有属性。方法是在属性名之前,使用#表示。#x就表示私有属性x,它也可以用来写私有方法

class Foo {
  #a=1;//私有属性
  #b;//私有属性
  #sum() { //私有方法
	return #a + #b; 
  }
  printSum() { console.log(#sum()); }
  constructor(a, b) { #a = a; #b = b; }
}


私有属性也可以设置 getter 和 setter 方法

class Counter {
  #xValue = 0;

  get #x() { return #xValue; }
  set #x(value) {
    this.#xValue = value;
  }

  constructor() {
    super();
    // ...
  }
}


上面代码中,#x是一个私有属性,它的读写都通过get #x()和set #x()来完成


四.this指向



类的方法内部如果含有this,它默认指向类的实例

。getName方法中的this,默认指向ThisStu类的实例。但是,如果将这个方法提取出来单独使用,this会指向该方法运行时所在的环境,因为找不到name方法而导致报错。

//ThisStu.js  
class ThisStu{  
 
    getName(){  
        return this.name();  
    }  
    name(){  
        return '王五';  
    }  
  
}  
export {ThisStu};  
  
//test.vue 
import {ThisStu} from './ThisStu';  
let thisStu = new ThisStu();  
console.log(thisStu.getName());  
const {getName} = thisStu;  
getName();  
//Cannot read property 'name' of undefined



一个比较简单的解决方法是,

在构造方法中绑定this,这样就不会找不到name方法了

。修改ThisStu.js文件如下:

//ThisStu.js  
class ThisStu{  
    // 构造  
    constructor() {  
        this.getName = this.getName.bind(this);  
    }  
  
    getName(){  
        return this.name();  
    }  
  
    name(){  
        return '王五';  
    }  
  
}  
export {ThisStu};


使用构造函数,直接给当前实例的getName赋值,修改修改ThisStu.js文件的构造函数如下:

// 构造  
constructor() {  
    //this.getName = this.getName.bind(this);  
    this.getName = ()=>{  
        return this.name();  
    }  
}  


五.方法


1.Class 的取值函数(getter)和存值函数(setter)



取值函数(getter)和存值函数(setter)可以自定义赋值和取值行为。当一个属性只有getter没有setter的时候,我们是无法进行赋值操作的,第一次初始化也不行。如果把变量定义为私有的(定义在类的外面),就可以只使用getter不使用setter。

//GetSet.js  
let data = {};  
  
class GetSet{  
  
    // 构造  
    constructor() {  
        this.width = 10;  
        this.height = 20;  
    }  
  
    get width(){  
        console.log('获取宽度');  
        return this._width;  
    }  
  
    set width(width){  
        console.log('设置宽度');  
        this._width = width;  
    }  
    //当一个属性只有getter没有setter的时候,我们是无法进行赋值操作的,第一次初始化也不行。  
    //bundle.js:8631 Uncaught TypeError: Cannot set property width of #<GetSet> which has only a getter  
  
  
    get data(){  
        return data;  
    }  
    //如果把变量定义为私有的,就可以只使用getter不使用setter。  
  
}  
  
let getSet = new GetSet();  
console.log("=====GetSet=====");  
console.log(getSet.width);  
getSet.width = 100;  
console.log(getSet.width);  
console.log(getSet._width);  
console.log(getSet.data);  
  
//存值函数和取值函数是设置在属性的descriptor对象上的。  
var descriptor = Object.getOwnPropertyDescriptor(  
    GetSet.prototype, "width");  
console.log("get" in descriptor);//true  
console.log("set" in descriptor);//true  


如果把上面的get和set改成以下形式,不加下划线报

Uncaught RangeError: Maximum call stack size exceeded

错误。这是因为,在构造函数中执行this.name=name的时候,就会去调用set name,在set name方法中,我们又执行this.name = name,进行无限递归,最后导致栈溢出(RangeError)。

get width(){  
    console.log('获取宽度');  
    return this.width;  
}  
  
set width(width){  
    console.log('设置宽度');  
    this.width = width;  
}  



以上width的getter和setter只是给width自定义存取值行为,开发者还是可以通过_width绕过getter和setter获取width的值。



补充:



Class的继承(extends)和自定义存值(setter)取值(getter)的整个案例:


//ExtendStuParent.js  
const ExtendStuParent = class ExtendStuParent{  
  
    name;//定义name  
    age;//定义age  
  
    // 构造  
    constructor(name,age) {  
        //用于写不能实例化的父类  
        if (new.target === ExtendStuParent) {  
            throw new Error('ExtendStuParent不能实例化,只能继承使用。');  
        }  
        this.name = name;  
        this.age = age;  
    }  
  
    getName(){  
        return this.name;  
    }  
  
    getAge(){  
        return this.age;  
    }  
};  
  
ExtendStuParent.prototype.width = '30cm';  
  
export default ExtendStuParent;  
  
//ExtendStu.js  
import ExtendStuParent from './ExtendStuParent';  
  
export default class ExtendStu extends ExtendStuParent{  
  
    // 构造  
    constructor(name, age, height) {  
        super(name,age);  
        this.height = height;  
        //父类和子类都有实例属性name,但是在toString方法调用getName的时候,  
        //返回的是子类的的数据  
        this.name = 'LiSi 子类';  
  
        //  
        this.color = 'black';  
        super.color = 'white';  
        console.log(super.color);//undefined  
        console.log(this.color);//black  
    }  
  
    toString(){  
        console.log(super.age);//undefined  
        console.log(super.width);//30cm  
        return "name:"+ super.getName() + " age:"+this.age + " height:"+this.height;  
    }  
  
}  


2.Class 的 Generator 方法


如果某个方法之前加上星号(*),就表示该方法是一个 Generator 函数

class Foo {
  constructor(...args) {
    this.args = args;
  }
  * [Symbol.iterator]() {
    for (let arg of this.args) {
      yield arg;
    }
  }
}

for (let x of new Foo('hello', 'world')) {
  console.log(x);
}
// hello
// world


上面代码中,Foo类的Symbol.iterator方法前有一个星号,表示该方法是一个 Generator 函数。Symbol.iterator方法返回一个Foo类的默认遍历器,for…of循环会自动调用这个遍历器。


3.

new.target属性




new是从构造函数生成实例的命令。ES6为new命令引入了一个new.target属性,(在构造函数中)返回new命令作用于的那个构造函数。如果构造函数不是通过new命令调用的,new.target会返回undefined,因此这个属性可以用来确定构造函数是怎么调用的。

class Targettu{  
    // 构造  
    constructor() {  
        if(new.target !== undefined){  
            this.height = 10;  
        }else{  
            throw new Error('必须通过new命令创建对象');  
        }  
    }  
}  
//或者(判断是不是通过new命令创建的对象下面这种方式也是可以的)  
class Targettu{  
    // 构造  
    constructor() {  
        if(new.target === Targettu){  
            this.height = 10;  
        }else{  
            throw new Error('必须通过new命令创建对象');  
        }  
    }  
}  
  
let targettu = new Targettu();  
//Uncaught Error: 必须通过new命令创建对象  
//let targettuOne = Targettu.call(targettu); 



需要注意的是,子类继承父类时,new.target会返回子类。通过这个原理,可以写出不能独立使用、必须继承后才能使用的类。

// 构造  
constructor(name,age) {  
    //用于写不能实例化的父类  
    if (new.target === ExtendStuParent) {  
        throw new Error('ExtendStuParent不能实例化,只能继承使用。');  
    }  
    this.name = name;  
    this.age = age;  
}  




六.class的静态方法



类相当于实例的原型,所有在类中定义的方法,都会被实例继承。如果在一个方法前,加上static关键字,就表示该方法不会被实例继承,而是直接通过类来调用,这就称为“静态方法”。


class Foo {
  static classMethod() {
    return 'hello';
  }
}


Foo.classMethod() // 'hello'


var foo = new Foo();
foo.classMethod()// TypeError: foo.classMethod is not a function


父类的静态方法,可以被子类继承

class Foo {
  static classMethod() {
    return 'hello';
  }
}

class Bar extends Foo {
}

Bar.classMethod() // 'hello'




注意:


1.如果静态方法包含this关键字,这个this指的是类,而不是实例


2.静态方法可以与非静态方法重名。

class Foo {
  static bar () {
    this.baz();
  }
  static baz () {
    console.log('hello');
  }
  baz () {
    console.log('world');
  }
}

Foo.bar() // hello


静态方法bar调用了this.baz,这里的this指的是Foo类,而不是Foo的实例,等同于调用Foo.baz


3.

静态方法只能在静态方法中调用,不能再实例方法中调用



七.Class静态属性和实例属性




静态属性指的是 Class 本身的属性,即Class.propName,而不是定义在实例对象(this)上的属性。Class 内部只有静态方法,没有静态属性。

class Foo {
}

Foo.prop = 1;
Foo.prop // 1


八.class的继承


(1).

基本用法+super关键字



Class 之间可以通过extends关键字实现继承, 这比 ES5 的通过修改原型链实现继承, 要清晰和方便很多。

class Point {
}

class ColorPoint extends Point {
}



上面代码定义了一个ColorPoint类,

该类通过extends关键字, 继承了Point类的所有属性和方法



但是由于没有部署任何代码, 所以这两个类完全一样, 等于复制了一个Point类

。 下面, 我们在ColorPoint内部加上代码。

class ColorPoint extends Point {  
    constructor(x, y, color) {  
        super(x, y); //  调用父类的 constructor(x, y)  
        this.color = color;  
    }  
    toString() {  
        return this.color + ' ' + super.toString(); //  调用父类的 toString()  
    }  
}  



上面代码中, constructor方法和toString方法之中, 都出现了

super关键字, 它在这里表示父类的构造函数, 用来新建父类的this对象








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



//ExtendStu.js  
//正确   构造  
constructor(name, age, height) {  
    super(name,age);  
    this.height = height;  
}  
  
//错误  构造  
constructor(name, age, height) {  
    this.height = height;  
    super(name,age);  
    //SyntaxError: 'this' is not allowed before super()  
}  


上面代码中,子类的constructor方法没有调用super之前,就使用this关键字,结果报错,而放

在super方法之后就是正确的




ES5的继承,实质是先创造子类的实例对象this,然后再将父类的方法添加到this上面(Parent.apply(this))。ES6的继承机制完全不同,实质是先创造父类的实例对象this(所以必须先调用super方法),然后再用子类的构造函数修改this。如果子类没有定义constructor方法,这个方法会被默认添加。


1.

super作为函数时,指向父类的构造函数。super()只能用在子类的构造函数之中,用在其他地方就会报错



class ExtendStuParent {
  constructor() {
    console.log(new.target.name);
  }
}
class ExtendStu extends ExtendStuParent {
  constructor() {
    super();
  }
}
new ExtendStuParent() // ExtendStuParent
new ExtendStu() // ExtendStu


注意:new.target指向当前正在执行的函数。可以看到, super虽然代表了父类ExtendStuParent的构造函数,但是返回的是子类ExtendStu的实例,即super内部的this指的是ExtendStu,因此super()在这里相当于ExtendStuParent.prototype.constructor.call(this)。


2.

super作为对象时,指向父类的原型对象


class A {
  p() {
    return 2;
  }
}

class B extends A {
  constructor() {
    super();
    console.log(super.p()); // 2
  }
}

let b = new B();


上面代码中,子类B当中的super.p(),就是将super当作一个对象使用。这时,super在普通方法之中,指向A.prototype,所以super.p()就相当于A.prototype.p()。


这里需要注意,

由于super指向父类的原型对象,所以定义在父类实例上的方法或属性,是无法通过super调用的


class A {
  constructor() {
    this.p = 2;
  }
}

class B extends A {
  get m() {
    return super.p;
  }
}

let b = new B();
b.m // undefined


上面代码中,p是父类A实例的属性,super.p就引用不到它。



属性定义在父类的原型对象上,super就可以取到



class A {}
A.prototype.x = 2;

class B extends A {
  constructor() {
    super();
    console.log(super.x) // 2
  }
}

let b = new B();


上面代码中,属性x是定义在A.prototype上面的,所以super.x可以取到它的值。



ES6 规定,

在子类普通方法中通过super调用父类的方法时,方法内部的this指向当前的子类实

例。


class A {
  constructor() {
    this.x = 1;
  }
  print() {
    console.log(this.x);
  }
}

class B extends A {
  constructor() {
    super();
    this.x = 2;
  }
  m() {
    super.print();
  }
}

let b = new B();
b.m() // 2


上面代码中,super.print()虽然调用的是A.prototype.print(),但是A.prototype.print()内部的this指向子类B的实例,导致输出的是2,而不是1。也就是说,实际上执行的是super.print.call(this)。



由于this指向子类实例,所以如果通过super对某个属性赋值,这时super就是this,赋值的属性会变成子类实例的属性




最后,由于对象总是继承其他对象的,所以可以在任意一个对象中,使用super关键字。

var obj = {
  toString() {
    return "MyObject: " + super.toString();
  }
};

obj.toString(); // MyObject: [object Object]


(2).类的prototype属性和__proto__属性



Class 作为构造函数的语法糖, 同时有prototype 属性和__proto__属性, 因此同时存在两条继承链。




( 1) 子类的__proto__属性, 表示构造函数的继承, 总是指向父类。





( 2) 子类prototype属性的__proto__属性, 表示方法的继承, 总是指向父类的prototype属性。

class A {}  
class B extends A {}  
B.__proto__ === A // true  
B.prototype.__proto__ === A.prototype // true  



子类B的__proto__属性指向父类A, 子类B的prototype属性的__proto__属性指向父类A的prototype属性。




这样的结果是因为, 类的继承是按照下面的模式实现的。



class A {}  
class B {}  
// B 的实例继承 A 的实例  
Object.setPrototypeOf(B.prototype, A.prototype);  
// B 继承 A 的静态属性  
Object.setPrototypeOf(B, A);  


这两条继承链,可以这样理解:作为一个对象,子类(B)的原型(__proto__属性)是父类(A);作为一个构造函数,子类(B)的原型对象(prototype属性)是父类的原型对象(prototype属性)的实例。

Object.create(A.prototype);
// 等同于
B.prototype.__proto__ = A.prototype;


(3).

Extends 的继承目标



extends关键字后面可以跟多种类型的值。

class B extends A {}


讨论三种特殊情况:


1.

子类继承 Object 类

class A extends Object {}  
A.__proto__ === Object // true  
A.prototype.__proto__ === Object.prototype // true  
这种情况下, A其实就是构造函数Object的复制, A的实例就是Object的实例。

2.

不存在任何继承

class A {}  
A.__proto__ === Function.prototype // true  
A.prototype.__proto__ === Object.prototype // true  
这种情况下, A 作为一个基类( 即不存在任何继承), 就是一个普通函数, 所以直接继承Funciton.prototype。 但是, A调用后返回一个空对象( 即Object实例), 所以A.prototype.__proto__指向构造函数( Object) 的prototype属性。

3.

子类继承null

class A extends null {}  
A.__proto__ === Function.prototype // true  
A.prototype.__proto__ === undefined // true  


这种情况与第二种情况非常像。 A也是一个普通函数, 所以直接继承Funciton.prototype。 但是, A 调用后返回的对象不继承任何方法, 所以它的__proto__指向Function.prototype, 即实质上执行了下面的代码。

class C extends null {  
    constructor() {  
        return Object.create(null);  
    }  
}  


(4).

Object.getPrototypeOf()




Object.getPrototypeOf方法可以用来从子类上获取父类。


Object.getPrototypeOf(ColorPoint) === Point  // true



因此, 可以使用这个方法判断, 一个类是否继承了另一个类。



(5).

实例的 __proto__ 属性



子类实例的 __proto__ 属性的 __proto__ 属性, 指向父类实例的 __proto__ 属性。 也就是说, 子类的原型的原型, 是父类的原型。

class A{}  
class B extends A{}  
let a = new A();  
let b = new B();  
console.log(b.__proto__ === a.__proto__);//false  
console.log(b.__proto__.__proto__ === a.__proto__);//true 



因此,通过子类实例的__proto__.__proto__属性,可以修改父类实例的行为。

b.__proto__.__proto__.getName = ()=>{  
    console.log('给父类添加一个函数');  
};  
b.getName();//给父类添加一个函数  
a.getName();//给父类添加一个函数  



使用子类的实例给父类添加getName方法,由于B继承了A,所以B和A中都添加了getName方法



(6).原生构造函数的继承


原生构造函数是指语言内置的构造函数, 通常用来生成数据结构。 ECMAScript 的原生构造函数大致有下面这些。

Boolean()  
Number()  
String()  
Array()  
Date()  
Function()  
RegExp()  
Error()  
Object()  



以前, 这些原生构造函数是无法继承的, 比如, 不能自己定义一个Array的子类。

function MyArray() {  
  Array.apply(this, arguments);  
}  
  
MyArray.prototype = Object.create(Array.prototype, {  
  constructor: {  
    value: MyArray,  
    writable: true,  
    configurable: true,  
    enumerable: true  
  }  
});  



上面代码定义了一个继承Array的MyArray类。但是,这个类的行为与Array完全不一致。

var colors = new MyArray();  
colors[0] = "red";  
colors.length  // 0  
  
colors.length = 0;  
colors[0]  // "red" 



之所以会发生这种情况,是因为子类无法获得原生构造函数的内部属性,通过Array.apply()或者分配给原型对象都不行。原生构造函数会忽略apply方法传入的this,也就是说,原生构造函数的this无法绑定,导致拿不到内部属性。ES5是先新建子类的实例对象this,再将父类的属性添加到子类上,由于父类的内部属性无法获取,导致无法继承原生的构造函数。比如,Array构造函数有一个内部属性[[DefineOwnProperty]],用来定义新属性时,更新length属性,这个内部属性无法在子类获取,导致子类的length属性行为不正常。





ES6允许继承原生构造函数定义子类,因为ES6是先新建父类的实例对象this,然后再用子类的构造函数修饰this,使得父类的所有行为都可以继承。下面是一个继承Array的例子。

//ExtendsArray.js  
class ExtendsArray extends Array{}  
  
let extendsArray = new ExtendsArray();  
console.log("=====ExtendsArray=====");  
extendsArray[0] = '数据1';  
console.log(extendsArray.length);  



上面代码定义了一个ExtendsArray类,继承了Array构造函数,因此就可以从ExtendsArray生成数组的实例。这意味着,ES6可以自定义原生数据结构(比如Array、String等)的子类,这是ES5无法做到的。上面这个例子也说明,extends关键字不仅可以用来继承类,还可以用来继承原生的构造函数。因此可以在原生数据结构的基础上,定义自己的数据结构。



(7).Mixin模式的实现


Mixin模式指的是,将多个类的接口“混入”(mix in)另一个类。它在ES6的实现如下。

/MixinStu.js  
export default function mix(...mixins) {  
    class Mix {}  
  
    for (let mixin of mixins) {  
        copyProperties(Mix, mixin);  
        copyProperties(Mix.prototype, mixin.prototype);  
    }  
  
    return Mix;  
}  
  
function copyProperties(target, source) {  
    for (let key of Reflect.ownKeys(source)) {  
        if ( key !== "constructor"  
            && key !== "prototype"  
            && key !== "name"  
        ) {  
            let desc = Object.getOwnPropertyDescriptor(source, key);  
            Object.defineProperty(target, key, desc);  
        }  
    }  
}  



上面代码的mix函数,可以将多个对象合成为一个类。使用的时候,只要继承这个类即可。

class MixinAll extends MixinStu(B,Serializable){  
  
    // 构造  
    constructor(x,y,z) {  
        super(x,y);  
        this.z = z;  
    }  
  
}  


九.引用

1.队列类 应用 var q=new Queue([1,2,3,4]);  q.shift();删除

 class Queue{
            constructor(content=[]){
                this._queue=[...content];
            }
            //删除
            shift(){
                const value=this._queue[0];
                this._queue.shift();
                return value;
            }
            //增加
            push(n){
                this._queue.push(n);
                return this._queue.length;
            }
        }

        var q=new Queue([1,2,3,4]);

        q.shift();
        q.push(5);
        console.log(q._queue);

2.简单的选项卡

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>选项卡</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0">
    <meta name="apple-mobile-web-app-capable" content="yes">
    <meta name="apple-mobile-web-app-status-bar-style" content="black">
    <style>
        .on{ background: #f60; color: #fff}
        .box div{
            width:200px;
            height:200px;
            border: 1px solid #000;
            display: none;
        }
    </style>
    <script>
        //选项卡
        class Tab{
            constructor(id){
                this.oBox=document.getElementById(id);
                this.aBtn=this.oBox.getElementsByTagName('input');
                this.aDiv=this.oBox.getElementsByTagName('div');
                this.init();
            }
            init(){
                for(let i=0; i<this.aBtn.length; i++){
                    this.aBtn[i].οnclick=function(){
                        this.iNow=i;
                        this.hide();
                        this.show(i);
                    }.bind(this);//重新绑定this的指向
                }
            }
            hide(){
                for(let i=0; i<this.aBtn.length; i++){
                    this.aBtn[i].className='';
                    this.aDiv[i].style.display='none';
                }
            }
            show(index){
                this.aBtn[index].className='on';
                this.aDiv[index].style.display='block';
            }
        }
        //继承
        class AutoTab extends Tab{//第二要用,则继承前一个就好
        }


        window.οnlοad=function(){
            new Tab('box');
            new AutoTab('box2');
        };
    </script>
</head>
<body>
    <div id="box" class="box">
        <input class="on" type="button" value="aaa">
        <input type="button" value="bbb">
        <input type="button" value="ccc">
        <div style="display: block;">1111</div>
        <div>2222</div>
        <div>3333</div>
    </div>
    <div id="box2" class="box">
        <input class="on" type="button" value="aaa">
        <input type="button" value="bbb">
        <input type="button" value="ccc">
        <div style="display: block;">1111</div>
        <div>2222</div>
        <div>3333</div>
    </div>
</body>
</html>








版权声明:本文为gao_xu_520原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。