Javascript hasOwnProperty always false on Event objects?
Asked Answered
S

2

6

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);
Shoeshine answered 31/7, 2015 at 18:54 Comment(0)
O
4

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:

enter image description here

Octagonal answered 31/7, 2015 at 20:1 Comment(1)
May I ask where did this diagram come from?Pizza
G
0

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.

Generalship answered 31/7, 2015 at 19:9 Comment(1)
ooops! thanks eddyjs. that was a typo when copying it - in the real code it's the same name. :)Shoeshine

© 2022 - 2024 — McMap. All rights reserved.