为什么事件属性不容易获得? [英] Why event properties are not easy to get?
问题描述
我有以下代码( 这里 是可编辑的示例-用法:在输入字段中输入并观看控制台):
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">
问题:
- 为什么仅在
keysForIn
中可以看到所有(?)事件字段/属性,但是在keys
和keysOwnProp
中却只有一个:isTrusted
? -
keysForIn
是否有替代方法(如果是,请提供)?
- Why only in
keysForIn
I see all(?) event fields/properties, but inkeys
andkeysOwnProp
only one:isTrusted
? - Is there an alternative for
keysForIn
(if yes, provide it) ?
推荐答案
在这里我复制粘贴GrégoryNEUT 答案-看起来是最好的答案:
Here I copy-paste Grégory NEUT answer - which looks like is the best one:
Object.keys(...)
返回对象的非符号可枚举属性的名称,但仅返回未继承的属性的名称.
Object.keys(...)
returns the names of the non-symbol enumerable properties of the object, but only the ones which are not inherited.
For...in
迭代对象的非符号可枚举属性的名称,无论是否继承.
For...in
iterates the names of the non-symbol enumerable properties of the object, inherited or not.
Object.getOwnPropertyNames(...)
返回所有非符号属性(是否可枚举).
Object.getOwnPropertyNames(...)
returns all non-symbol properties (enumerable or not).
据我所知,for ... in
除了获得继承的属性外别无选择
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);
这篇关于为什么事件属性不容易获得?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!