码迷,mamicode.com
首页 > 其他好文 > 详细

[ES6] Use ES6 Proxies

时间:2017-01-12 11:52:48      阅读:166      评论:0      收藏:0      [点我收藏+]

标签:intercept   use   ott   sed   ...   rmi   sel   back   ons   

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

标签:intercept   use   ott   sed   ...   rmi   sel   back   ons   

原文地址:http://www.cnblogs.com/Answer1215/p/6275341.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!