HuangHongRui / Notebook

:pencil2: Yeah.. This's My NoteBook...:closed_book:
0 stars 0 forks source link

Es6_Javascript中的类 [表达式] #21

Open HuangHongRui opened 7 years ago

HuangHongRui commented 7 years ago

类跟函数一样. 都有两种存在形式

函数声明 和 类声明 由相应关键字 ( function & class) 进行定义, 随后紧跟标识符

表达式形式的 函数 和 类 与之相似.. 只是不需要在关键字后面添加 标识符..

类表达式的 设计初衷 是为了声明相应变量或传入函数作为参数.

HuangHongRui commented 7 years ago

(基本)类表达式语法

let PersonClass = class {
  constructor (name){
    this.name = name
  }
  sayName() {
    console.log(this.name)
  }
}
let person = new PersonClass('Raine')
person.sayName() // "Raine"

类声明 和 类表达式 的功能极为相似, 只是代码编写方式略有差异.

两者最重要的区别: name 属性不同. 匿名类表达式的 name 属性值为 空字符串. 而类声明的 name 属性的 name 属性值为 类名..

HuangHongRui commented 7 years ago

命名类-表达式

跟函数一样, 都可以定义为 命名表达式 , 声明时, 在关键字后添加一个标识符即可定义为 命名类表达式.

let person = class PersonClass {
    constructor(name) {
        this.name = name
    }
    sayname() {
        console.log(this.name)
    }
}
console.log( typeof person ) // "function"
console.log( typeof PersonClass ) // "undefined"

由于 PersonClass 只存在于类定义中,因此可被用在 sayname() 这样的方法中. 而在类外部, 由于不存在 一个名为 PersonClass 的绑定, 所以值为 'undefined'

HuangHongRui commented 7 years ago

下面Code, 等价于上面Code..

let PersonClass = (function() {
    "use strict"
    const PersonClass2 = function(name) {
        if (typeof new.target === "undefined") {
            throw new Error('用new调用')
        }
        this.name = name
    }
    Object.defineProperty(PersonClass2.prototype, "sayname", {
        value: function(){
            if( typeof new.target !== "undefined") {
                throw new Error('无需new调用')
            }
            console.log(this.name)
        },
        enumerable: false,
        writable: true,
        configurable: true
    })
    return PersonClass2
}())

let 定义的外部绑定 与 通过 const 定义的内部绑定具有相同名称. 对于命名类表达式 通过 const 定义名称, 从而PersonClass2 只能在类的内部使用.