【问题标题】:Why event properties are not easy to get?为什么事件属性不容易获取?
【发布时间】:2018-11-29 15:20:02
【问题描述】:

我有以下代码(HERE 是可编辑的示例 - 用法:在输入字段中输入并观看控制台):

function test(event) 
{	  
  let keys = Object.keys(event);
  let keysOwnProp = Object.getOwnPropertyNames(event);
  let keysForIn=[]; for(let k in event) { keysForIn.push(k); }


  console.log('keysForIn',keysForIn);
  console.log('keys',JSON.stringify(keys));
  console.log('keysOwnProp',JSON.stringify(keysOwnProp));
}
<input oninput="test(event)" placeholder="type something">

问题

  • 为什么我只在keysForIn 中看到所有(?)事件字段/属性,但在keyskeysOwnProp 中只有一个:isTrusted
  • keysForIn 是否有替代方案(如果有,请提供)?

【问题讨论】:

    标签: javascript object events properties


    【解决方案1】:

    似乎Object.keys & Object.getOwnPropertyNames 给出了仅属于对象的属性,而for..in 循环也将给出继承的属性

    document.getElementById('test').addEventListener('input', function(event) {
      let keys = Object.keys(event);
      let keysOwnProp = Object.getOwnPropertyNames(event);
      // location is one of the property which we get on using for..in
      console.log(event.hasOwnProperty('location'))
      let keysForIn = [];
      for (let k in event) {
        keysForIn.push(k);
      }
    })
    <input id="test">

    【讨论】:

    • 你能提供一些 jsfiddle 的证据吗?而且,如何区分对象中的某些字段/属性是否被继承?那么输入事件只有一个非继承字段/属性(isTrust)?
    • 好的,所以现在我们知道hasOwnProperty 也无法访问for-in 拥有的属性...但是为什么(还有其他选择)?
    【解决方案2】:

    我在这里复制粘贴 Grégory NEUT 答案 - 看起来是最好的:

    Object.keys(...) 返回对象的非符号可枚举属性的名称,但只返回那些未被继承的。

    For...in 迭代对象的非符号可枚举属性的名称,无论是否继承。

    Object.getOwnPropertyNames(...) 返回所有非符号属性(可枚举或不可枚举)


    据我所知,除了 for ... in 之外别无他法来获取继承的属性

    function displayDetail(o) {
      let keys = Object.keys(o);
    
      console.log('Object.keys > ', keys);
    
      let keysOwnProp = Object.getOwnPropertyNames(o);
    
      console.log('getOwnPropertyNames > ', keysOwnProp);
    
      const keysForIn = [];
    
      for (let k in o) {
        keysForIn.push(k);
      }
    
      console.log('for ... in > ', keysForIn);
    }
    
    
    /**
     * The basic object
     */
    const obj = {
      own: 'A',
    };
    
    /**
     * We add a non enumerable property to the object
     */
    Object.defineProperty(obj, 'notEnumerable', {
      enumerable: false,
      value: 123,
    });
    
    /**
     * We create a new object based on the first (it will inherit it's properties)
     */
    const objWithInheritedProperties = Object.create(obj);
    
    console.log('REGULAR OBJECT\n');
    displayDetail(obj);
    
    console.log('\n-----------\n');
    
    console.log('OBJECT WITH INHERITANCE\n');
    displayDetail(objWithInheritedProperties);

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-08-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-07-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多