为什么事件属性不容易获得?

时间:2018-11-29 15:20:03

标签: javascript object events properties

我有以下代码( 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是否有替代方法(如果可以,请提供)?

2 个答案:

答案 0 :(得分:0)

Object.keysObject.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">

答案 1 :(得分:0)

在这里我复制粘贴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);