ES6-17 class與對象

class

  • 模擬類的方式
  • 語法糖(把以前的寫法換了一個方式)

類內部的方法是不可枚舉的

  • ES5用Object.assign拓展的原型屬性是可枚舉的
function Point(x, y) {this.x = x;this.y = y;
}
// 這樣定義的原型上方法eat\drink是可枚舉的
Point.prototype = Object.assign(Point.prototype, {eat: function () { },drink: function () { },
})

在這里插入圖片描述

  • ES6定義的公有屬性是不可枚舉的
class Point {constructor(x, y) {// 實例化的屬性配置:私有屬性this.x = x;this.y = y;}// 公有屬性:原型上的方法toString() {return '(' + this.x + ', ' + this.y + ')';}
}
const p = new Point(1, 1)
console.log(p)
console.log(p.toString())

在這里插入圖片描述

默認指定constructor

class Point{}
const p = new Point()
console.log(p)

在這里插入圖片描述

class Foo {constructor() {return Object.create(null);}
}new Foo() instanceof Foo
// false

表達式寫法和IIFE

// 看起來很怪異
let Point = class { }
const p = new Point()
console.log(p)let person = new class Person { }()
console.log(person)  

在這里插入圖片描述

let person = new class Person {constructor(name, age) {this.name = name;this.age = age;}
}('Lee', 10)
console.log(person)

在這里插入圖片描述

存在TDZ 不可提升

ES7私有屬性新寫法

  • class可以定義公有方法,不可定義公有屬性
class Point {// ES7新寫法,依然是私有屬性x = 1;y = 1;// 公有屬性:原型上的方法toString() {return '(' + this.x + ', ' + this.y + ')';}
}
console.log(new Point().toString()) // (1,1)

公有屬性的私有方法

Symbol

const _print = Symbol()
console.log(_print)
class Point {// ES7新寫法,依然是私有屬性x = 1;y = 1;// 公有屬性:原型上的方法toString() {return '(' + this.x + ', ' + this.y + ')';}[_print]() {console.log('公有屬性私有化')}
}
console.log(new Point().toString()) // (1,1)
new Point()[_print]() // 公有屬性私有化
// new Point()._print() // 這樣訪問不到 
console.log(new Point())

在這里插入圖片描述

將方法定義到class外部

  • class內部不能直接使用x y
class Point {x = 1;y = 1;print() {// 注意 這里不能直接使用x y_print.call(this, this.x, this.y);}}
function _print(x, y) {console.log(this.x, this.y)
}
new Point().print() // 1 1
console.log(new Point())

在這里插入圖片描述

static靜態方法

  • 只能是方法不能是屬性?

類中定義取值、存值函數

class Point {get a() {console.log('取值函數')}set b(val) {console.log('存值函數', val)}
}
const p = new Point()
p.a // 取值函數
p.b = 10 // 存值函數 10

類中默認使用了嚴格模式

繼承extends

name為什么為什么不報錯
在這里插入圖片描述

super

  • super可以指向原型對象
let proto = {y: 20,z: 40
}
let obj = {x: 10,foo() {console.log(super.y)}
}
Object.setPrototypeOf(obj, proto)
obj.foo() // 20

轉譯ES5

Object.keys(Object.prototype) // []
  1. TDZ
  2. use strict
  3. 不可枚舉
  4. 只能通過new方式調用
  5. 不傳參數不會報錯
class Person {constructor(name = 'Lee', age = "18") {this.name = name;this.age = age;}say() {console.log('say')}drink() {console.log('drink')}static eat() {console.log('static eat')}
}
"use strict"; // 嚴格模式// 只能通過new方式調用 new方式調用下,this才指向實例
function _classCallCheck(instance, Constructor) {if (!(instance instanceof Constructor)) {throw new TypeError("Cannot call a class as a function");}
}function _defineProperties(target, props) {for (var i = 0; i < props.length; i++) {var descriptor = props[i];// 原型上的屬性默認是不可枚舉的descriptor.enumerable = descriptor.enumerable || false;descriptor.configurable = true;if ("value" in descriptor) descriptor.writable = true;Object.defineProperty(target, descriptor.key, descriptor);}
}// 傳入構造器 公有方法(在原型上的方法)靜態方法(只能通過類調用)
function _createClass(Constructor, protoProps, staticProps) {if (protoProps) _defineProperties(Constructor.prototype, protoProps);if (staticProps) _defineProperties(Constructor, staticProps);return Constructor;
}// 函數表達式 變量聲明提升 TDZ
var Person = /*#__PURE__*/function () {function Person() {// 參數默認值var name = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 'Lee';var age = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : "18";_classCallCheck(this, Person);this.name = name;this.age = age;}_createClass(Person, [{key: "say",value: function say() {console.log('say');}}, {key: "drink",value: function drink() {console.log('drink');}}], [{key: "eat",value: function eat() {console.log('static eat');}}]);return Person;
}();

裝飾器

  • npm install -D @babel/plugin-proposal-decorators
  • 淘寶npm鏡像pm i babel-plugin-transform-decorators-legacy --save-dev --registry=https://registry.npm.taobao.org
  • 配置babelrc
  • 沒安裝前,在瀏覽器運行代碼報錯Uncaught SyntaxError: Invalid or unexpected token
  • npx babel app.js --watch --out-file bundle/app.js 實時監聽
{"presets": ["@babel/preset-env"],"plugins": [["@babel/plugin-proposal-decorators", { "legacy": true }]]
}
@testable
class Person {constructor(name = 'Lee', age = "18") {this.name = name;this.age = age;}say() {console.log('say')}drink() {console.log('drink')}}
let person = new Person()
console.log('person', person) // person Person { name: 'Lee', age: '18' }
function testable(target) {console.log('testable', target) // testable [Function: Person]
}

在這里插入圖片描述

  • 安裝插件后打包,在index.html中引入打包后的文件,瀏覽器打印出正確結果
    在這里插入圖片描述
@testable
class Person {constructor(name = 'Lee', age = "18") {this.name = name;this.age = age;}@readOnlysay() {console.log('say hi')}
}
let person = new Person()
person.say()
function testable(target) {console.log('testable', target)
}
function readOnly(target, name, descriptor) {
// target - 原型
// name - 方法名
// descriptor - 該方法的屬性描述符console.log('readOnly', target, name, descriptor)
}

使用場景 - 埋點

  • 在原本的功能上添加埋點功能
class AD {@log('show')show() {console.log('ad is show')}@log('click')click() {console.log('ad is click')}
}
let ad = new AD()
ad.show()
function log(type) {return function (target, name, descriptor) {let src_fn = descriptor.value; // 函數體descriptor.value = (...args) => {src_fn.apply(target, args);// 以下是埋點要做的console.log('埋點', type)}}
}

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/250980.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/250980.shtml
英文地址,請注明出處:http://en.pswp.cn/news/250980.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

8.8 正睿暑期集訓營 Day5

目錄 2018.8.8 正睿暑期集訓營 Day5總結A 友誼巨輪(線段樹 動態開點)B 璀璨光滑C 構解巨樹考試代碼ABC2018.8.8 正睿暑期集訓營 Day5時間&#xff1a;3.5h(實際)期望得分&#xff1a;602020實際得分&#xff1a;202020 比賽鏈接這里也有一些 總結 線段樹&#xff01;&#xff0…

算法 --- 二叉樹的最大深度

思路: 1.二叉樹的深度,等于Max(左子樹最大深度,右子樹最大深度) 1 2.節點不存在時,此時的深度為0 3.當節點存在,左右子樹不存在時(此時為葉子節點) 返回1 /*** Definition for a binary tree node.* function TreeNode(val) {* this.val val;* this.left this.righ…

ES6-18/19 異步的開端-promise

ES6-18異步的開端-promise ES6-19 promise的使用方法和自定義promisify try catch只能捕獲同步異常&#xff0c;不能捕獲異步的 等待所有異步都執行完&#xff0c;打印結果&#xff0c;比較笨拙的方法&#xff0c;在每個異步操作加arr.length 3 && show(arr) Promis…

leetcode35 C++ 4ms 搜索插入位置

class Solution { public:int searchInsert(vector<int>& nums, int target) {for(int i 0;i<nums.size();i){if(nums[i] > target){return i;}}return nums.size()-1;} }; 轉載于:https://www.cnblogs.com/theodoric008/p/9449049.html

OpenCV-Python 中文教程(搬運)目錄

OpenCV-Python 中文教程 OpenCV官方教程中文版&#xff08;For Python&#xff09; OpenCV2-Python-Tutorials 段力輝 譯 說明&#xff1a;搬運自linux公社pdf文件&#xff0c;粗略搬運&#xff0c;僅作個人筆記參考&#xff0c;有時間再美化 部分文件參考&#xff1a; https:/…

算法 --- 平衡二叉樹

解題思路: 1.首先寫一個返回深度的函數d 2.寫一個遍歷函數t 3.在t中首先判斷,r是否為空(為空則此時就是平衡二叉樹,返回true),然后判斷是否為葉子節點(r.left null && r.right null)若是則返回true,最后判斷,其左子樹的深度與右子樹的深度之差是否大于1.若是則返回fal…

【co】ES6-20/21 iterator與generator

ES6-20 iterator與generator ES6-21 async與await、ES6的模塊化 try catch不能捕獲異步異常 try catch是同步代碼 try {setTimeout(() > {console.log(a)}) } catch (e) {console.log(e) }iterator 內部迭代器&#xff1a;系統定義好的迭代器接口&#xff08;如數組Symbol…

嵌入式系統UBOOT

一個完整的嵌入式linux系統包含4部分內容&#xff1a;Bootloader、Parameters、Kernel、Root File System。3、4、5、6部分詳細介紹了這4部分的內容&#xff0c;這是Linux底層軟件開發人員應該掌握的。通過學習這些章節&#xff0c;您可以詳細了解到如何在一個裸板上裁減、移植…

驅動芯片

一 LED驅動芯片&#xff1a; 1.1 TM1640:16位數碼管驅動芯片&#xff0c;2線制控制&#xff08;CLK/DIN&#xff09;,SCLK低電平時DIN輸入&#xff0c;而SCLK高電平時保持DIN保持不變&#xff1b;開始傳輸&#xff1a;SCLKH時DIN由高變低&#xff0c;停止傳輸SCLKH時DIN由由低變…

jquery --- 控制元素的隱藏/顯示

<!DOCTYPE html> <html> <head> <meta charset"utf-8"> </head> <body> <div id"panel"><h5 class"head">什么是jquery?</h5><div class"content" style"display:non…

confusion_matrix(混淆矩陣)

作者&#xff1a;十歲的小男孩 凡心所向&#xff0c;素履可往 目錄 監督學習—混淆矩陣 是什么&#xff1f;有什么用&#xff1f;怎么用&#xff1f; 非監督學習—匹配矩陣 混淆矩陣 矩陣每一列代表預測值&#xff0c;每一行代表的是實際的類別。這個名字來源于它可以非常容…

Python 21 Django 實用小案例1

實用案例 驗證碼與驗證 KindEditor 組合搜索的實現 單例模式 beautifulsoup4 驗證碼與驗證 需要安裝Pillow模塊 pip stall pillow1、首先需要借助pillow模塊用來畫一個驗證碼圖形&#xff0c;這里單獨封裝了一個py文件&#xff0c;調用一個方法就好了 1 #!/user/bin/env python…

jquery --- 事件處理函數的event對象的幾個屬性(方法)說明

1.event.type: 事件的類型 $(a).click(function(event) {alert(event.type);return false; // 阻止鏈接跳轉 }); // click2.event.preventDefault(): 阻止默認事件 $("#sub").bind("click", function(event) {var username $("#username").va…

數據恢復軟件

鏈接&#xff1a;https://pan.baidu.com/s/1n6x5vhW-3SY8MAvvnqVtog 密碼&#xff1a;thh0轉載于:https://www.cnblogs.com/huanu/p/9452039.html

VMware

1.VMware軟件安裝&#xff1a; https://jingyan.baidu.com/article/9f7e7ec09da5906f281554d6.html 2&#xff0c;鏡像文件下載地址&#xff1a;http://www.cnbeta.com/articles/tech/566773.htm 有圖形界面。 或是在官網&#xff1a;https://wiki.centos.org/Download 2.cento…

jquery --- 全選、全不選、反選、提交

注意:jquery 提供的$(’#id’).attr(‘checked’,true)方法,在某些情況下會失效… 因此,使用js原生的 .checked true方法 控制 // html <form>你愛好的運動是? <br/><input type"checkbox" name"items" value"足球" /> 足球…

【重要】ES6-23 JavaScript模塊化

前端js模塊化的演變發展 模塊化解決的問題 傳統模塊化、插件化 CommonJS AMD/CMD ES6模塊化 ES6以前 沒有js引擎 一開始js寫在html的script標簽里js內容增多&#xff0c;抽取出index.js文件&#xff0c;外部引入js再增加&#xff0c;index.html對應index.js index2.html對應ind…

Quartz.Net定時任務EF+MVC版的web服務

之前項目采用JAVA 的 Quartz 進行定時服調度務處理程序&#xff0c;目前在.NET下面使用依然可以完成相同的工作任務&#xff0c;其實什么語言不重要&#xff0c;關鍵是我們要學會利用語言實現價值。它是一個簡單的執行任務計劃的組件&#xff0c;基本包括這三部分&#xff1a;J…

jquery --- 多選下拉框的移動(穿梭框)

效果如下: 幾個注意地方: 1.多選下拉框需要添加 multiple 2.獲取選中的元素KaTeX parse error: Expected EOF, got # at position 3: (#?id option:selec…(#id option:not(:selected)) 下面是代碼的各個部分實現, 方便引用,最后是總體代碼,方便理解 添加選中到右邊: // …

ES6-24 生成器與迭代器的應用

手寫生成器 先done再false&#xff0c;不然index就提前了一步1 var arr [1,2] function generator(arr){var i 0;return{next(){var done i > arr.length ? true : false,value done ? undefined : arr[i];return {value : value,done : done} }} } var gen gener…