Javascript 是否有一种不那么麻烦的方法来检索原型链中的getter和setter方法?

Javascript 是否有一种不那么麻烦的方法来检索原型链中的getter和setter方法?,javascript,getter-setter,prototypal-inheritance,Javascript,Getter Setter,Prototypal Inheritance,我有一个对对象的引用,该对象在其原型链的某个地方有一个特定属性的getter和setter。我想获得getter和setter方法的引用,以及它们所在的对象。我知道我可以通过手动迭代每个原型对象并检查hasOwnProperty,如以下代码片段所示: const obj2=(()=>{ 常量baseProto={ 获取道具(){ 返回“propval”; }, 设置道具(newVal){ log('setting…'); } }; const obj1=Object.create(basePr

我有一个对对象的引用,该对象在其原型链的某个地方有一个特定属性的getter和setter。我想获得getter和setter方法的引用,以及它们所在的对象。我知道我可以通过手动迭代每个原型对象并检查
hasOwnProperty
,如以下代码片段所示:

const obj2=(()=>{
常量baseProto={
获取道具(){
返回“propval”;
},
设置道具(newVal){
log('setting…');
}
};
const obj1=Object.create(baseProto);
返回Object.create(obj1);
})();
//从对obj2的引用中,想要获得getter或setter方法,
//并希望在不调用它们的情况下获取它们所在的对象:
设currentObj=obj2;
const propToFind='prop';
让我们开始,开始,开始;
while(currentObj){
if(currentObj.hasOwnProperty(propToFind)){
foundProto=当前OBJ;
({get,set}=Object.getOwnPropertyDescriptor(currentObj,propToFind));
打破
}
currentObj=Object.getPrototypeOf(currentObj);
}
if(foundProto){
log('Found:',get,set,foundProto);
}
这看起来相当麻烦,
循环很难看

我不认为这很麻烦,这只是当你试图在原型链的任何地方找到一个属性时必须做的事情

当循环时,您不必编写
,当然,迭代可以很容易地表示为
for循环:

let get, set, foundProto;
for (let currentObj = obj2; currentObj; currentObj = Object.getPrototypeOf(currentObj)) {
  if (currentObj.hasOwnProperty('prop')) {
    foundProto = currentObj;
    ({ get, set } = Object.getOwnPropertyDescriptor(currentObj, 'prop'));
    break;
  }
}
if (foundProto) {
  console.log('Found:', get, set, foundProto);
}
当然,您也可以编写一个助手函数来实现这一点,如

function getInheritedPropertyDescriptor(obj, prop) {
  for (; obj != null; obj = Object.getPrototypeOf(obj)) {
    if (Object.prototype.hasOwnProperty.call(obj, prop)) {
      return { foundProto: obj, ...Object.getOwnPropertyDescriptor(obj, prop) };
    }
  }
  return null;
}
var result = getInheritedPropertyDescriptor(obj2, 'prop');
if (result) {
  console.log('Found:', result.get, result.set, result.foundProto);
}
“无法与它们(或它们所在的原型对象)交互。”-你想做什么?通常情况下,您不需要直接访问函数,这就是为什么没有额外的语法来简化它。