Why event properties are not easy to get?

2020-05-09 18:43发布

问题:

I have following code ( HERE is editable example - usage: type in input field and watch console):

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">

Questions:

  • Why only in keysForIn I see all(?) event fields/properties, but in keys and keysOwnProp only one: isTrusted?
  • Is there an alternative for keysForIn (if yes, provide it) ?

回答1:

It seems Object.keys & Object.getOwnPropertyNames gives the properties which belongs solely to the object where as for..in loop will also give the inherited properties

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">



回答2:

Here I copy-paste Grégory NEUT answer - which looks like is the best one:

Object.keys(...) returns the names of the non-symbol enumerable properties of the object, but only the ones which are not inherited.

For...in iterates the names of the non-symbol enumerable properties of the object, inherited or not.

Object.getOwnPropertyNames(...) returns all non-symbol properties (enumerable or not).


To my knowledge there is no alternative to for ... in to get inherited properties

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);