简体   繁体   English

Javascript传递对象作为函数参数

[英]Javascript passing object as function parameter

I'm quite new to javascript, so maybe it's a silly error. 我对javascript很新,所以也许这是一个愚蠢的错误。 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. 问题是,当我调用test()时,我得到objA(objA.func1和objA.func2)中的函数执行。 I would like just to get the properties value of objA. 我想获得objA的属性值。 I have to use another function and an array, fill the array with the properties of objA and then pass the array: 我必须使用另一个函数和一个数组,用objA的属性填充数组,然后传递数组:

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. 函数对象的属性(它们是第一类值),因此它们像任何其他属性一样出现在for (var propName in myObj)循环中。 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: 或者,在现代浏览器中,您可以使特定属性(如您的函数) 不可枚举 ,因此它们不会出现在for ... in循环中:

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

For more on this, see the docs for Object.defineProperty or Object.defineProperties . 有关详细信息,请参阅Object.definePropertyObject.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: 最后,如果您不需要将函数定义为闭包 ,则可以在对象的原型上定义它们,在这种情况下, hasOwnProperty测试将导致它们被跳过:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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