问题
I was hoping somebody could help clarify the hasOwnProperty() method with relation to Event Objects.
I am trying to clone a mouse event (eventually this object will be passed to an iframe) I have already built a 'clone' function - but whenever i attempt to clone a window event (ie scroll, click etc) all instances of 'hasOwnProperty()' return false. For example, i iterate over the object - using hasOwnProperty() to check - and each property is returning false. This works for standard objects - but not event objects.
Is this because all of the properties within the event objects are inherited? Or is there an issue with the code?
Any enlightenment would be appreciated :)
Code snippet:
function cloneObject (o_node) {
var newObject = {};
for (var child_node in o_node) {
if (o_node.hasOwnProperty(child_node)) {
//no object properties are returning true at this point.
newObject[child_node] = o_node[child_node];
}else{
console.log("!hasOwnProperty()");
}
}
return newNode;
}
function onclick(e){
var cloned_object_e = cloneObject(e); //returns an empty object;
}
window.addEventListener('click', onclick);
回答1:
Your assumption is correct - the e
argument is a hollow new MouseEvent
object that has no own properties, only those inherited from the prototype chain MouseEvent<-UIEvent<-Event
. Here's the inheritance diagram:
回答2:
You created an object called newObject
, but you returned an object called newNode
, which you never defined or added anything to. Try changing your return statement to this:
return newObject;
I think this will give you an object with some properties that the event itself has.
来源:https://stackoverflow.com/questions/31753224/javascript-hasownproperty-always-false-on-event-objects