es6-类

timg.jpg

前言

最近这两天有点不在状态,感觉有种无形的压力压在身上,变的异常的暴躁了,唉,前端这条路真的走对了吗?算了,敲代码吧。

类声明

要声明一个类,首先使用class关键字,紧接着是类的名字,然后其他内部方法和属性类似于对象的字面量写法

 class PersonClass{
        //定义一个类似es5写法的构造函数,通过关键字constructor
            constructor(name){
                      this.name = name
            }
       //定义方法
          sayName(){
                  console.log(this.name);
}
}
let person = new PersonClass("ly");
person.sayName();
console.log(person instanceof PersonClass);
console.log(person instanceof Object);

console.log(typeof PersonClass);
console.log(typeof  PersonClass.prototype.sayName);
a.png

es5对应的等价代码

let PersonType2 = (function(){
    "use strict"
    const PersonType2 = function(name){
        //确保通过关键字new调用该函数
        if(typeof new.target === "undefined"){
            throw new Error("必须通过new来创建")
        }
    }
    Object.defineProperty(PersonType2.prototype,'sayName',{
        value:function(){
            //确保不通过关键字new调用该函数
        if(typeof new.target !== "undefined"){
            throw new Error("不能通过new来创建")
        }
        console.log(this.name)
        },
        enumerable:false,
        writable:true,
        configurable:true
    })
    return PersonType2;
}())

类表达式

跟函数一样他也存在表达式写法,好像还很雷同

 let PersonClass = class {
        //定义一个类似es5写法的构造函数,通过关键字constructor
            constructor(name){
                      this.name = name
            }
       //定义方法
          sayName(){
                  console.log(this.name);
}
}
let person = new PersonClass("ly");
person.sayName();
console.log(person instanceof PersonClass);
console.log(person instanceof Object);

console.log(typeof PersonClass);
console.log(typeof  PersonClass.prototype.sayName);

上述两种类的写法,它不会出现变量提升的现象,所以我们的那种写法,对结果没啥太大区别

类也将作为一等公民

一等公民是指一个可以传入的函数,可以从函数返回,并且可以赋值给变量的值

//像这样的方式
function createObject(classDef){
      return new ClassDef();
}
let objClass = createObject(class {
      sayHi() {
      console.log('hi');
}
})

//函数表达式还有一种调用方式,就是通过立即调用类构造函数可以创建单例

let person = new class{
      constructor(name){
              this.name = name;  
      }
       sayName() {
        console.log(this.name);
}
}('ly')
person.sayName() //ly

访问器属性

类支持在构造函数下创建自己的属性,但是类也支持直接在原型上定义访问器的属性,通过get和set来获得值或者设置值

class Person {
    constructor(name) {
        this.name = name;
    }
    set ages(age) {
        return this.age = age;
    }
    get ages() {
        return this.age+10;
    }
}

let person = new Person('ly');

person.ages = 18
console.log(person.ages);
person.agess = 18
console.log(person.agess);

var descriptor = Object.getOwnPropertyDescriptor(Person.prototype,'ages');
console.log("get" in descriptor); //true
console.log("set" in descriptor);//true
console.log(descriptor.enumerable); //false

生成器方法与类的结合

class MyClass {
    * createIterator() {
        yield 1;
        yield 2;
        yield 1;
    }
}
var b = new MyClass()
var a = b.createIterator();
console.log(a.next());
console.log(a.next());
console.log(a.next());
console.log(a.next());
a.png

我们可以通过Symbol.iterator属性定义一个默认的类迭代器

class Collection {
    constructor() {
        this.items = []
    }
    *[Symbol.iterator]() {
        yield * this.items.entries();
    }
}
var collection = new Collection();

collection.items.push(1)
collection.items.push(12)
collection.items.push(16)

for (const x of collection) {
    console.log(x);
}
a.png

静态成员

es5来模拟静态成员

function PersonType(name){
    this.name = name;
    
}

//静态方法
PersonType.create = function(name){
    return new PersonType(name)
}

//实例方法
PersonType.prototype.sayName = function(){
    console.log(this.name);
}

var person = PersonType.create("ly");
person.name = "li"
console.log(person); //ly  (不是很懂静态成员是干嘛的,就是为了让构造函数也能像普通函数一样挂在函数吗?)

在es可以通过 static来创建静态成员

class PersonClass {
    constructor(name){
        this.name = name;
    }
    sayName(){
        console.log("hi")
    }

    static create(name){
        return new PersonClass(name)
    }
}

let person = PersonClass.create('ly');

console.log(person.name); //ly

继承与派生类

在es6之前继承需要这么长的代码,而且haibuyi

function Reactangle(length,width){
    this.length = length;
     this.width = width;
}

Reactangle.prototype.getArea = function(){
    return this.length*this.width;
}

function Square(length){
    Reactangle.call(this,length,length)
}

Square.prototype = Object.create(Reactangle.prototype,{
    constructor:{
        value:Square,
        enumerable:true,
        writeable:true,
        configurable:true
    }
})

var square = new Square(4);

console.log(square.getArea()); //16
console.log(square instanceof Square);//true
console.log(square instanceof Reactangle);//true

这样的类继承更加 清晰

class Reactangle {
    constructor(length, width) {
        this.length = length;
        this.width = width;
        console.log(this.length,this.width);
    }
    getArea() {
        
        return this.length * this.width
    }
}
class Square extends Reactangle {
    constructor(length) {
        
        super(length, length)
    }
}

var square = new Square(3);

console.log(square.getArea()); //9
console.log(square instanceof Square); //true

这是super的默认是设置

class Squery extends Reactangle {

}

//等价于

class Square extends Reactangle {
    constructor(...args){
        super(...args);
    }
}

类方法遮蔽

派生类中的方法总会覆盖基类中的同名方法。这种覆盖只是屏蔽

class Reactangle {
    constructor(length, width) {
        this.length = length;
        this.width = width;
        console.log(this.length,this.width);
    }
    getArea() {
        
        return this.length * this.width
    }
}
class Square extends Reactangle {
     getArea() {
         return this.length*this.length;
     }
}

我们也可以屏蔽之后在调用

class Reactangle {
    constructor(length, width) {
        this.length = length;
        this.width = width;
        console.log(this.length,this.width);
    }
    getArea() {
        return this.length * this.width
    }
}
class Square extends Reactangle {
     getArea() {
         return super.getArea();
     }
}

var square = new Square(3,3);

console.log(square.getArea()); //9
console.log(square instanceof Square); //true

静态成员继承

通过static创建的静态成员,静态变量不能被子类继承

class Reactangle {
    constructor(length, width) {
        this.length = length;
        this.width = width;
        console.log(this.length,this.width);
    }
    getArea() {
        
        return this.length * this.width
    }

    static create(length,width){
        return new Reactangle(length,width)
    }
}
class Square extends Reactangle {
     getArea() {
         return super.getArea();
     }
}

var square = Square.create(3,4);

console.log(square.getArea()); //9
console.log(square instanceof Square); //true

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

派生自表达式的类

只要一个函数具有[Constuctor]属性和原型

function Reactangle(length,length){
    this.length = length;
    this.width  = width;

}

Reactangle.prototype.getArea = function(){
    return this.length*this.width
}

class Square extends Reactangle {
     constructor (length) {
         super(length,length)
     }
}

var square = new Square(3);

console.log(square.getArea()); //9
console.log(square instanceof Square); //true

继承的高级用法

下面的栗子可以动态确定使用那个基类,更好的辅助开发

let SerializableMixin = {
    serialize(){
        return JSON.stringify(this)
    }
}

let AreaMixin = {
    getArea() {
        return this.length*this.width;
    }
}


function mixin(...mixins){
    var base = function(){};
    Object.assign(base.prototype,...mixins);
    return base;
}

class Square extends mixin (AreaMixin,SerializableMixin) {
      constructor (length){
          super();
          this.length = length;
          this.width = length;
      }
}

var x = new Square(3)
console.log(x.getArea())  //9
console.log(x.serialize()) //{"length":3,"width":3}

类的Symbol.species属性

Symbol.species 是指定一个构造函数创建派生对象的函数值属性,比如当我们继承一个Array时,我们调用其方法产生的对象将不再是原始的类而是派生出来的类,比如

class MyArray extends Array {

}

let items = new MyArray(1,3,4,5),
    subitems = items.map(item => item*2);

console.log(items instanceof MyArray); //true
console.log(subitems instanceof MyArray); //true
console.log(items instanceof Array);  //true
console.log(subitems instanceof Array); //true

但是实际上也不是这么一回事,于是我加了这段代码

class MyArray extends Array {
    static get [Symbol.species](){
        return RegExp;
    }
}

let items = new MyArray(1,3,4,5),
    subitems = items.map(item => item*2);

console.log(items instanceof MyArray); //true
console.log(subitems instanceof MyArray); //false
console.log(items instanceof Array);  //true
console.log(subitems instanceof Array); //false

mdn 的解释一下代码参考下

你可能想在扩展数组类 MyArray 上返回 Array 对象。 例如,当使用例如 map() 这样的方法返回默认的构造函数时,你希望这些方法能够返回父级的 Array 对象,以取代 MyArray 对象。Symbol.species 允许你这么做

class MyArray extends Array {
    // 覆盖 species 到父级的 Array 构造函数上
    static get [Symbol.species]() { return Array; }
  }
  var a = new MyArray(1,2,3);
  var mapped = a.map(x => x * x);
  
  console.log(mapped instanceof MyArray); // false
  console.log(mapped instanceof Array);   // true

但是即使不这么做我也是可以返回他的父级方法,有点鸡肋? 再说

在累的构造函数使用new.target

之前在构造函数如果要求必须通过new来创建是这样写的


function Add(name){
    console.log(new.target=== Add) //true
    if(typeof new.target=="undefined"){
        throw new Error('必须通过new创建')
    }
    this.name = name;
}

var a = new Add('ly');

现在可以怎么写


class Add {
    constructor(name){
        this.name = name;
        console.log(new.target=== Add) //true
    }
}

var a = new Add('ly');

构造函数不通过new创建的实例,new.target为undefined

function Add(name){
    console.log(new.target) //true
    if(typeof new.target=="undefined"){
        throw new Error('必须通过new创建')
    }
    this.name = name;
}

var a =Add('ly');

类则是无论如何都有值,因为必须new啊 不然报错

我们可以用这样的方式定义基类,基类不可被创建,只能被继承

class Add {
    constructor(name){
        if(new.target===Add){
            throw new Error('基类不可被继承')
        }
        this.name = name;
    }
}
class SubAdd extends Add {
    constructor(name){
        super(name)
        
    }
}
// var a = new Add('ly'); //报错   基类不可被继承

var b= new SubAdd('hh')
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 159,458评论 4 363
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,454评论 1 294
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 109,171评论 0 243
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 44,062评论 0 207
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,440评论 3 287
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,661评论 1 219
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,906评论 2 313
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,609评论 0 200
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,379评论 1 246
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,600评论 2 246
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,085评论 1 261
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,409评论 2 254
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,072评论 3 237
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,088评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,860评论 0 195
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,704评论 2 276
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,608评论 2 270

推荐阅读更多精彩内容

  • 引用:http://www.tuicool.com/articles/BFf6jiB 从本质上说,ES6的clas...
    开车去环游世界阅读 1,290评论 0 3
  • 第一章:块级作用域绑定 块级声明 1.var声明及变量提升机制:在函数作用域或者全局作用域中通过关键字var声明的...
    BeADre_wang阅读 762评论 0 0
  • 面向对象的语言都有一个类的概念,通过类可以创建多个具有相同方法和属性的对象,ES6之前并没有类的概念,在ES6中引...
    Erric_Zhang阅读 1,060评论 1 4
  • 假如我们想要创建一个经典的面向对象设计示例:Circle类。想象一下我们正在为一个简单的Canvas库编写这个Ci...
    糖心m阅读 371评论 0 2
  • 2016年,剩下最后一天了,回顾我的2016年,是简单而又平凡的一年,我用闲暇时间抒怀畅意,表达着我的欢喜...
    bai素心若雪阅读 210评论 3 5