I’m quite new to javascript, so maybe it’s a silly error.
I created an object like the follwing:
function objA(){
this.prop1;
this.prop2;
this.prop3;
this.func1=function(){
alert('func1');
}
this.func2=function(){
alert('func2');
}
}
I now have a function where I want to pass the object:
var foo=new objA;
function test(foo){....}
The problem is that when I call test(), I get the functions in objA (objA.func1 and objA.func2) executed.
I would like just to get the properties value of objA.
I have to use another function and an array, fill the array with the properties of objA and then pass the array:
var arrayA={}
function fillArray(data){
arrayA.prop1=data.prop1;
arrayA.prop2=data.prop2;
arrayA.prop3=data.prop3;
}
function test(arrayA){....}
Is it the only way or I’m doing something wrong ?
Functions are properties of an object (they are first-class values), and thus they show up in
for (var propName in myObj)loops like any other property. You can avoid examining them further via:Alternatively, in modern browsers you can make specific properties (like your functions) non-enumerable, so they won’t show up in a
for ... inloop:For more on this, see the docs for
Object.definePropertyorObject.defineProperties.Finally, if you don’t need to define your functions as closures you can define them on the prototype of your object in which case the
hasOwnPropertytest will cause them to be skipped: