2017-05-29 44 views
0
var funcSetter = { 

    defineProperty: function(target, prop, descriptor) { 
     if (prop) { 
      let temp = descriptor.value; 
      descriptor.value = temp => { 
       if (temp.startsWith('_')) { 
        temp = "Default Value Attached , no Underscores allowed"; 
        return temp; 
       } else return temp; 
      }; 
     } 
     return true; 
    } 
}; 

let proxy_3 = new Proxy(obj_3, funcSetter); 

Object.defineProperty(proxy_3, 'no', { 
    value: '_Bharath', 
    writable: true, 
    enumerable: true, 
    configurable: true 
}); 

我這裏面臨的問題是,當我打電話陷阱definePropertydescriptor.value下定義的箭頭功能不被調用,點擊底部的迴歸真實,並設置爲undefined爲什麼我從defineProperty方法中得到一個未定義的值?

屬性的值

我很確定我沒有正確使用箭頭功能。任何人都可以引導我走向正確的方向嗎?

謝謝你的所有提示。非常感激!

+0

請添加一些用例。 –

+0

這是一些東西,我在JS中學習代理和反思時正在進行試驗。本身沒有用例。 – Bharath

+0

* defineProperty方法必須返回一個布爾值,指示該屬性是否已被成功定義* - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy/handler/defineProperty #Return_value –

回答

1

有兩個問題:

  1. 你只是分配箭頭功能descriptor.value。不叫它。
  2. 你其實不是設置任何地方的財產。

我想這應該解決的問題

var funcSetter = { 
 

 
    defineProperty: function(target, prop, descriptor) { 
 
    if (prop) { 
 
     let temp = descriptor.value; 
 
     // Use an IIFE 
 
     descriptor.value = (temp => { 
 
     if (temp.startsWith('_')) { 
 
      return "Default Value Attached , no Underscores allowed"; 
 
     } else { 
 
      return temp; 
 
     }; 
 
     })(temp); 
 
    } 
 
    // Use Reflect.defineProperty to actually set the property 
 
    return Reflect.defineProperty(target, prop, descriptor); 
 
    } 
 
}; 
 

 
let obj_3 = {}; 
 
let proxy_3 = new Proxy(obj_3, funcSetter); 
 

 
Object.defineProperty(proxy_3, 'no', { 
 
    value: '_Bharath', 
 
    writable: true, 
 
    enumerable: true, 
 
    configurable: true 
 
}); 
 

 
console.log(obj_3);

此外,MUCH簡單的方法來做到這一點

var funcSetter = { 
 

 
    defineProperty: function(target, prop, descriptor) { 
 
    if (prop) { 
 
     if (descriptor.value.startsWith('_')) { 
 
     descriptor.value = "Default Value Attached , no Underscores allowed"; 
 
     } 
 
    } 
 
    // Use Reflect.defineProperty to actually set the property 
 
    return Reflect.defineProperty(target, prop, descriptor); 
 
    } 
 
} 
 
let obj_3 = {}; 
 
let proxy_3 = new Proxy(obj_3, funcSetter); 
 

 
Object.defineProperty(proxy_3, 'no', { 
 
    value: '_Bharath', 
 
    writable: true, 
 
    enumerable: true, 
 
    configurable: true 
 
}); 
 

 
console.log(obj_3);

+0

生命遠遠超過工程設計。 –

+0

我同意。試圖用最少的修改來更改OP的代碼。正常的'if..else'實際上應該足夠了。 –

+0

我嘗試了一個更簡單的方法來解決這個問題,並解決了這個問題,但是它讓我不明白爲什麼箭頭函數方法不起作用。 – Bharath

相關問題