javascript入門_JavaScript代理快速入門

javascript入門

What is a JavaScript proxy? you might ask. It is one of the features that shipped with ES6. Sadly, it seems not to be widely used.

什么是JavaScript代理? 你可能會問。 這是ES6附帶的功能之一。 可悲的是,它似乎并未得到廣泛使用。

According to the MDN Web Docs:

根據MDN網絡文檔 :

The Proxy object is used to define custom behavior for fundamental operations (e.g. property lookup, assignment, enumeration, function invocation, etc).

Proxy對象用于定義基本操作的自定義行為(例如,屬性查找,賦值,枚舉,函數調用等)。

In simple terms, proxies are getters and setters with lots of swag. A proxy object sits between an object and the outside world. They intercept calls to the attributes and methods of an object even if those attributes and methods don’t exist.

簡單來說,代理是gettersetter方法有很多贓物。 代理對象位于對象和外界之間。 即使對象屬性和方法不存在,它們也會攔截對它們的調用。

For us to understand how proxies work, we need to define three terms used by proxies:

為了讓我們理解代理的工作方式,我們需要定義代理使用的三個術語:

  1. handler: The placeholder object which contains traps (they’re the interceptors).

    handler :包含陷阱的占位符對象(它們是攔截器)。

  2. traps: The methods that provide property access (they live inside the handler).

    traps :提供屬性訪問的方法(它們位于處理程序內部)。

  3. target: The object which the proxy virtualizes.

    target :代理虛擬化的對象。

句法 (Syntax)

let myProxy = new Proxy(target, handler);

為什么要代理? (Why proxies?)

Since proxies are similar to getters and setters, why should we use them? Let’s see why:

由于代理類似于gettersetter,我們為什么要使用它們? 讓我們看看為什么:

const staff = {_name: "Jane Doe",_age: 25,get name() {console.log(this._name);},get age() {console.log(this._age);},set age(newAge) {this._age = newAge;console.log(this._age)}
};
staff.name // => "Jane Doe"
staff.age // => 25
staff.age = 30
staff.age // => 30
staff.position // => undefined

Let’s write the same code with proxies:

讓我們用代理編寫相同的代碼:

const staff = {name: "Jane Doe",age: 25
}
const handler = {get: (target, name) => {name in target ? console.log(target[name]) : console.log('404 not found');},set: (target, name, value) => {target[name] = value;}
}
const staffProxy = new Proxy(staff, handler);
staffProxy.name // => "Jane Doe"
staffProxy.age // => 25
staffProxy.age = 30
staffProxy.age // => 30
staffProxy.position // => '404 not found'

In the above example using getters and setters, we have to define a getter and setter for each attribute in the staff object. When we try to access a non-existing property, we get undefined.

在上面的使用gettersetter的示例中,我們必須為staff對象中的每個屬性定義一個gettersetter 。 當我們嘗試訪問不存在的屬性時,我們得到undefined

With proxies, we only need one get and set trap to manage interactions with every property in the staff object. Whenever we try to access a non-existing property, we get a custom error message.

使用代理,我們只需要一個get and set陷阱即可管理與staff對象中每個屬性的交互。 每當我們嘗試訪問不存在的屬性時,都會收到自定義錯誤消息。

There are many other use cases for proxies. Let’s explore some:

代理還有許多其他用例。 讓我們探索一些:

代理驗證 (Validation with proxies)

With proxies, we can enforce value validations in JavaScript objects. Let’s say we have a staff schema and would like to perform some validations before a staff can be saved:

使用代理,我們可以在JavaScript對象中強制執行值驗證。 假設我們有一個staff模式,并且希望在保存職員之前執行一些驗證:

const validator = {set: (target, key, value) => {const allowedProperties = ['name', 'age', 'position'];if (!allowedProperties.includes(key)) {throw new Error(`${key} is not a valid property`)}if (key === 'age') {if (typeof value !== 'number' || Number.isNaN(value) || value <= 0) {throw new TypeError('Age must be a positive number')}}if (key === 'name' || key === 'position') {if (typeof value !== 'string' || value.length <= 0) {throw new TypeError(`${key} must be a valid string`)}}target[key] = value; // save the valuereturn true; // indicate success}
}
const staff = new Proxy({}, validator);
staff.stats = "malicious code" //=> Uncaught Error: stats is not a valid property
staff.age = 0 //=> Uncaught TypeError: Age must be a positive number
staff.age = 10
staff.age //=> 10
staff.name = '' //=> Uncaught TypeError: name must be a valid string

In the code snippet above, we declare a validator handler where we have an array of allowedProperties. In the set trap, we check if the key being set is part of our allowedProperties. If it’s not, we throw an error. We also check if the values being set are of certain data types before we save the value.

在上面的代碼片段中,我們聲明了一個validator處理程序,其中有一個allowedProperties數組。 在set陷阱中,我們檢查設置的鍵是否是我們allowedProperties一部分。 如果不是,則拋出錯誤。 在保存值之前,我們還檢查設置的值是否屬于某些數據類型。

可撤銷代理 (Revocable proxies)

What if we wanted to revoke access to an object? Well, JavaScript proxies have a Proxy.revocable() method which creates a revocable proxy. This gives us the ability to revoke access to a proxy. Let’s see how it works:

如果我們想撤消對某個對象的訪問該怎么辦? 嗯,JavaScript代理具有Proxy.revocable()方法,該方法創建可撤消的代理。 這使我們能夠撤消對代理的訪問。 讓我們看看它是如何工作的:

const handler = {get: (target, name) => {name in target ? console.log(target[name]) : console.log('404 not found');console.log(target)},set: (target, name, value) => {target[name] = value;}
}
const staff = {name: "Jane Doe",age: 25
}
let { proxy, revoke } = Proxy.revocable(staff, handler);
proxy.age // => 25
proxy.name // => "Jane Doe"
proxy.age = 30
proxy.age // => 30
revoke() // revoke access to the proxy
proxy.age // => Uncaught TypeError: Cannot perform 'get' on a proxy that has been revoked
proxy.age = 30 // => Uncaught TypeError: Cannot perform 'set' on a proxy that has been revoked

In the example above, we are using destructuring to access theproxy and revoke properties of the object returned by Proxy.revocable().

在上面的示例中,我們使用解構來訪問proxyrevoke Proxy.revocable()返回的對象的屬性。

After we call the revoke function, any operation applied to proxy causes a TypeError. With this in our code, we can prevent users from taking certain actions on certain objects.

調用revoke函數后,應用于proxy任何操作都會導致TypeError 。 使用此代碼,我們可以防止用戶對某些對象執行某些操作。

JavaScript proxies are a powerful way to create and manage interactions between objects. Other real world applications for Proxies include:

JavaScript代理是創建和管理對象之間的交互的強大方法。 代理的其他實際應用程序包括:

  • Extending constructors

    擴展構造函數
  • Manipulating DOM nodes

    操作DOM節點
  • Value correction and an extra property

    價值校正和額外的屬性
  • Tracing property accesses

    跟蹤屬性訪問
  • Trapping function calls

    陷阱函數調用

And the list goes on.

而這樣的例子不勝枚舉。

There’s more to proxies than we have covered here. You can check the Proxy MDN Docs to find out all the available traps and how to use them.

代理比我們在這里討論的更多。 您可以檢查“ 代理MDN文檔”以找到所有可用的陷阱以及如何使用它們。

I hope you found this tutorial useful. Please do and share so others can find this article. Hit me up on Twitter @developia_ with questions or for a chat.

希望本教程對您有所幫助。 請分享,以便其他人可以找到本文。 通過問題或聊天在Twitter @d evelopia_上打我。

翻譯自: https://www.freecodecamp.org/news/a-quick-intro-to-javascript-proxies-55695ddc4f98/

javascript入門

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

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

相關文章

linux缺少文件操作數,linux 文件的atime,ctime,mtime查看與修改

查看ls -a默認顯示的是修改時間ls -c / --timestatus / --timectime顯示的是狀態修改時間(即權限修改時間)ls -u / --timeuse / --timeaccess / --timeatime表示的是文件訪問時間修改touch: 缺少了文件操作數請嘗試執行“touch --help”來獲取更多信息。[weilocalhost ~]$ touc…

leetcode47. 全排列 II(回溯)

給定一個可包含重復數字的序列&#xff0c;返回所有不重復的全排列。 示例: 輸入: [1,1,2] 輸出: [ [1,1,2], [1,2,1], [2,1,1] ] 代碼 class Solution {List<List<Integer>> cListnew ArrayList<>();public List<List<Integer>> permuteUni…

linux 磁盤查看方式

fdisk (查看物理磁盤大小) df (查看文件系統&#xff0c;也就是正在使用磁盤大小) lsblk (查看邏輯磁盤大小)轉載于:https://www.cnblogs.com/MUQINGFENG123/p/10820345.html

ioslabel陰影,UILabel的內陰影

is it possible to create such a UILabel with inner and outer shadow?i only know shadowColor and shadowOffsetzoomed:thanks!解決方案The answer by dmaclach is only suitable for shapes that can easily be inverted. My solution is a custom view that works with …

Webpack初學者介紹

Webpack is a tool that lets you compile JavaScript modules. It’s also known as a module bundler.Webpack是使您可以編譯JavaScript模塊的工具。 也稱為模塊捆綁器 。 Given a large number of files, it generates a single file (or a few files) that run your app.給…

Android Coding利器之掌握小技巧,助你Coding更上一層樓~

本文講的是Android Coding利器之掌握小技巧&#xff0c;助你Coding更上一層樓~&#xff0c;話說前幾天在網上瀏覽到一大牛寫的關于Android布局優化的文章&#xff0c;看后感觸很深&#xff0c;回過頭看看自己寫過的代碼&#xff0c;發現還是有不少需要改進&#xff0c;今天找不…

linux系統報警怎么辦,常見Linux系統故障和解決方法

常見Linux系統故障和解決方法發布時間&#xff1a;2020-06-06 14:48:19來源&#xff1a;億速云閱讀&#xff1a;212作者&#xff1a;Leah欄目&#xff1a;云計算這篇文章給大家分享的是常見的Linux系統故障和解決方法。在使用系統的過程中總會有各種各樣的故障&#xff0c;所以…

Vuex 模塊化與項目實例 (2.0)

Vuex 強調使用單一狀態樹&#xff0c;即在一個項目里只有一個 store&#xff0c;這個 store 集中管理了項目中所有的數據以及對數據的操作行為。但是這樣帶來的問題是 store 可能會非常臃腫龐大不易維護&#xff0c;所以就需要對狀態樹進行模塊化的拆分。 首先貼出一個邏輯比較…

click js自動點擊 vue_vue.js2.0點擊獲取自己的屬性和jquery方法

如下所示&#xff1a;:data-index"index":dt"index"v-on:click"onclick($event,index)":data-d "JSON.stringify( item)"href"http://www.baidu.com" rel"external nofollow" rel"external nofollow"da…

Python:知識目錄

Python目錄 第一篇&#xff1a;數據類型部分文件操作 基礎數據類型---str 基礎數據類型---List 基礎數據類型---dict 基礎數據類型---set 基礎數據類型---bytes 數據類型的總結 文件操作------讀&#xff0c;寫 文件操作------使用方法 第二章&#xff1a;函數模塊 初識函數…

初學者css常見問題_5分鐘內學習CSS-初學者教程

初學者css常見問題關于網絡設計語言的快速教程。 (A quick tutorial on the design language of the web.) CSS (Cascading Style Sheets) is what makes web pages look good and presentable. It’s an essential part of modern web development and a must-have skill for …

leetcode39. 組合總和(回溯)

給定一個無重復元素的數組 candidates 和一個目標數 target &#xff0c;找出 candidates 中所有可以使數字和為 target 的組合。 candidates 中的數字可以無限制重復被選取。 說明&#xff1a; 所有數字&#xff08;包括 target&#xff09;都是正整數。 解集不能包含重復的…

一臉懵逼學習基于CentOs的Hadoop集群安裝與配置(三臺機器跑集群)

1&#xff1a;Hadoop分布式計算平臺是由Apache軟件基金會開發的一個開源分布式計算平臺。以Hadoop分布式文件系統&#xff08;HDFS&#xff09;和MapReduce&#xff08;Google MapReduce的開源實現&#xff09;為核心的Hadoop為用戶提供了系統底層細節透明的分布式基礎架構。 注…

linux批量去掉文件名前綴,linux 批量刪除某個前綴文件

1. 命令 (參考&#xff1a;https://blog.csdn.net/kl28978113/article/details/80271831)find ./ -name updatesites*-* -exec rm {} \;2. 舉例[rootadmin batch-create-sites]# ls2020-02-13-10-10.out logs-2020-04-07-08-00.out updatesites-2020-02-12-01-49-25.xlsx updat…

Docker - 避免啟動container后運行shell腳本執行完成后docker退出container

問題 最近在使用 Dockerfile 啟動容器&#xff0c;發現使用Dockerfile調用容器里面的shell&#xff0c;當shell執行完成以后&#xff0c;docker會退出容器。 分析 Docker 在執行shell的時候&#xff0c;是在后臺執行的&#xff1b;因此&#xff0c;在shell執行完成以后&#xf…

css畫橫線箭頭_用CSS繪制三角形箭頭

用CSS繪制三角形箭頭。使用純CSS&#xff0c;你只需要很少的代碼就可以創作出各種瀏覽器都兼容的三角形箭頭&#xff01;CSS代碼:/* create an arrow that points up */div.arrow-up {width: 0;height: 0;border-left: 5px solid transparent; /* left arrow slant */border-ri…

Jmeter參數化的理解

jmeter參數化有兩種情況&#xff1a; jmeter執行的sql語句中值的參數化&#xff08;如select過濾條件&#xff09;csv data set config參數表示方式${zjhm}jmx腳本的設置屬性參數化&#xff0c;方便命令行調用時修改參數&#xff08;如并發量、執行時間&#xff09;在腳本中調用…

leetcode216. 組合總和 III(回溯)

找出所有相加之和為 n 的 k 個數的組合。組合中只允許含有 1 - 9 的正整數&#xff0c;并且每種組合中不存在重復的數字。 說明&#xff1a; 所有數字都是正整數。 解集不能包含重復的組合。 示例 1: 輸入: k 3, n 7 輸出: [[1,2,4]] 代碼 class Solution {List<List…

linux內核epub,Android底層開發技術實戰詳解——內核、移植和驅動(第2版)[EPUB][MOBI][AZW3][42.33MB]...

內容簡介本書從底層原理開始講起&#xff0c;結合真實的案例向讀者詳細介紹了Android內核、移植和驅動開發的整個流程。全書分為21章&#xff0c;依次講解驅動移植的必要性&#xff0c; Goldfish、OMAP內核和驅動解析&#xff0c;顯示系統、輸入系統、振動器系統、音頻系統、視…

機器學習崗位太少_太多的東西要學習,很少的時間

機器學習崗位太少by Rick West由里克韋斯特(Rick West) 太多的東西要學習&#xff0c;很少的時間 (So much to learn, so little time) 我學習&#xff0c;保持動力并實現目標的主要技巧 (My top tips for learning, staying motivated, and achieving your goals) One of the…