Javascript 将对象作为函数参数传递

Javascript passing object as function parameter

本文关键字:函数 参数传递 对象 Javascript      更新时间:2023-09-26

我对javascript很陌生,所以也许这是一个愚蠢的错误。我创建了一个类似于下面的对象:

function objA(){
    this.prop1;
    this.prop2;
    this.prop3;
    this.func1=function(){
        alert('func1');
    }
    this.func2=function(){
        alert('func2');
    }
}

我现在有一个函数,我想在其中传递对象:

var foo=new objA;
function test(foo){....}

问题是当我调用test((时,我执行了objA(objA.func1和objA.func2(中的函数。我只想获取 objA 的属性值。我必须使用另一个函数和一个数组,用 objA 的属性填充数组,然后传递数组:

var arrayA={}
function fillArray(data){
    arrayA.prop1=data.prop1;
    arrayA.prop2=data.prop2;
    arrayA.prop3=data.prop3;
}
function test(arrayA){....}

这是唯一的方法还是我做错了什么?

函数对象的属性(它们是一等值(,因此它们像任何其他属性一样显示在for (var propName in myObj)循环中。您可以通过以下方式避免进一步检查它们:

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
}

或者,在现代浏览器中,您可以将特定属性(如函数(设置为不可枚举,这样它们就不会显示在for ... in循环中:

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

有关此内容的更多信息,请参阅Object.definePropertyObject.defineProperties的文档。

最后,如果你不需要将函数定义为闭包,你可以在对象的原型上定义它们,在这种情况下,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