class(一)--类的创建
生活随笔
收集整理的這篇文章主要介紹了
class(一)--类的创建
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
class是ES6引入的,它并不是一種全新的繼承模式,而只是基于原型對象繼承封裝的語法糖,因此只要充分理解原型對象,原型鏈,繼承等知識,class也就很好容易理解了
類的聲明
ES5及之前是通過創建一個構造函數(Fn)以及將方法指派到該構造函數的原型對象(Fn.prototype)上,來創建一個類。
在ES6中類的聲明就十分簡單了,只要以class關鍵字開始, 接上類名, 最后將方法編寫在花括號{}里面。(注意點:方法之間不需要逗號,方法之間不需要逗號,方法之間不需要逗號)
class Person {// 等價于 Person構造函數constructor(name) {this.name = name;}// 等于Person.prototype.sayHellosayHello() {console.log(`Hello, my name is ${this.name}`);} }let me = new Person('mxk'); console.log(me.name); // mxk console.log(me.sayHello()) // Hello, my name is mxkconsole.log(me instanceof Person) // true console.log(typeof Person) //function console.log(Object.getPrototypeOf(me) === Person.prototype) // true console.log(Person.prototype.constructor === Person) // true類表達式
匿名函數表達式
let Person = class {constructor(name) { this.name = name; } }具名函數表達式
let Person = class Person1{constructor(name) { this.name = name; } }與函數的聲明和表達式不同,函數聲明是會被提升的,但是類的聲明和表達式都不存在提升,因此它們主要的不同就是代碼風格
類的特點
模擬類的創建
let/*不會被提升*/ Person /*外部可以訪問的*/ = (function() {"use strict"; /*運行在嚴格模式下*/const /*不能修改內部的類名*/ Person1 = function(name) {if (new.target === void 0) {throw new Error('構造函數必須使用new');}this.name = name;}Object.defineProperty(Person1.prototype, 'sayHello', {value: function() {if (new.target !== void 0) {throw new Error('類內方法調用不能使用new')}console.log(`Hello, my name is ${this.name}`);},enumerable: false, /*類內所有的方法都是不可枚舉的*/writable: true,configurable: true})return Person1; })();類的聲明和表達式基本是一致的,函數聲明暴露給外部的類名和內部的類名是相同的,類表達式的話只有賦值符號左邊的類名是我們可以訪問的,右側那個是內部的類名
立即調用類構造函數
let me = new class {constructor(name) { this.name = name; }sayHello() {console.log(`Hello, my name is ${this.name}`);} }('mxk');console.log(me.name) // mxk console.log(me.sayHello()) // Hello, my name is mxk使用這種模式你無法訪問到類,因為外部可以訪問的類名它并沒有暴露出來
訪問器屬性
class Person {constructor(name, age) {this.name = name;this.__age = age}get age() {return this.__age;}set age(value) {this.__age = value + 1;} } 相當于 Object.defineProperty(Person.prototype, 'age', {enumerable: false, /*不可枚舉*/configurable: true,get() { return this.__age; },set(value) { this.__age = value + 1; } })靜態成員
直接定義在構造函數對象上的方法,實例對象無法訪問到
class ClassType {constructor() {this.type = 'class_type';}static create() {return new ClassType();} }let ct = ClassType.create(); console.log(ct.type); //class_type console.log(ct.create); // undefined轉載于:https://www.cnblogs.com/guanine/p/9273098.html
總結
以上是生活随笔為你收集整理的class(一)--类的创建的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: C语言 - strcpy和strncpy
- 下一篇: js 简单弹框toast