下麵的例子定義了一個函數rectangleArea,它以寬度和高度為參數並返回矩形的麵積。該程序創建一個代理並為矩形區域函數定義一個處理程序對象。這個handler object在函數執行之前驗證傳遞給函數的參數數量。如果沒有將兩個參數傳遞給函數,處理程序對象將引發錯誤。
<script>
function rectangleArea(width,height){
return width*height;
}
const handler = {
apply:function(target,thisArgs,argsList){
console.log(argsList);
//console.log(target)
if(argsList.length == 2){
return Reflect.apply(target,thisArgs,argsList)
}
else throw 'Invalid no of arguments to calculate'
}
}
const proxy = new Proxy(rectangleArea,handler)
const result = proxy(10,20);
console.log('area is ',result)
proxy(10) // Error
</script>
上麵代碼的輸出將如下麵提到的那樣——
[10, 20] area is 200 [10] Uncaught Invalid no of arguments to calculate
相關用法
- ES6 handler.set()用法及代碼示例
- ES6 handler.get()用法及代碼示例
- ES6 handler.construct()用法及代碼示例
- ES6 handler.has()用法及代碼示例
- ES6 RegExp split()用法及代碼示例
- ES6 Array every()用法及代碼示例
- ES6 Array reduceRight()用法及代碼示例
- ES6 Reflect.set()用法及代碼示例
注:本文由純淨天空篩選整理自 ES6 - handler.apply()。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。