简体   繁体   中英

Javascript passing object as function parameter

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:

for (var prop in myObj){
  if (!myObj.hasOwnProperty(prop)) continue; // Skip inherited properties
  var val = myObj[prop];
  if (typeof val === 'function'))  continue; // Skip functions

  // Must be my own, non-function property
}

Alternatively, in modern browsers you can make specific properties (like your functions) non-enumerable , so they won't show up in a for ... in loop:

function objA(){
  this.prop1 = 42;
  Object.defineProperty(this,'func1',{
    value:function(){
     ...
    }
  });
}

For more on this, see the docs for Object.defineProperty or Object.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 hasOwnProperty test will cause them to be skipped:

function objA(){
  this.prop1 = 42;
}
objA.prototype.func1 = function(){
  // operate on the object generically
};

var a = new objA;
"func1" in a;              // true
a.hasOwnProperty("func1"); // false

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM