[ES6] Use ES6 Proxies

Posted Answer1215

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[ES6] Use ES6 Proxies相关的知识,希望对你有一定的参考价值。

A javascript Proxy allows you to intercept operations performed on objects, arrays, or functions like property lookup, assignment, invocation, property deletion, and more to add custom behavior. In this lesson we look at how to intercept property lookup with the get "trap" that will allow us to get items starting from the end of the array with ease.

 

console.clear()

const characters = [
  Harry Potter,
  Ron Weasly,
  Hermione Granger,
  Nevel Longbottom,
  Lavender Brown,
  Scabbers,
  Pigwidgeon,
]

const handler = {
  // target: the array itself
  // name: the index which passed in
 get(target, name) {
   
   // check whether index is 0,1...6
   if(name in target) {
     
     // if yes, then get the value back
     return Reflect.get(target, name)
   } else {
   
     // if not, then the name is -1, -2, -3...
     const index = Number(name);
     return Reflect.get(target, target.length + index)
   }
 }
}

const proxy = new Proxy(characters, handler)

console.log(proxy[3]); // Nevel Longbottom
console.log(proxy[0]); // Harry Potter
console.log(proxy[-2]); // Scabbers

 

以上是关于[ES6] Use ES6 Proxies的主要内容,如果未能解决你的问题,请参考以下文章

vue学习:解决Apycharm的 * is only available in ES6(use 'esversion: 6') 问题

js es6 Proxy

ES6深入浅出-13 Proxy 与 Reflect-2.Proxy 代理

ES6 模块串联

ES6解构赋值

Vue项目中提示JSHint: import is only available in ES6 (use esversion: 6)解决