-1

如何将实例化对象的属性作为参数传递给 JavaScript 函数。我想这样做,以便我被迫始终使用对象的相同属性。

我该怎么做呢?

//object
var house = {
    bed:"",
    chair:"",
    tv,""

};

//function
var doThis = function(OBJ){

    //pass this OBJ to something
    alert(OBJ.bed);
    alert(OBJ.chair);
    alert(OBJ.tv);


};


//call function
doThis({new house.bed = "a", new house.chair="c", new house.tv = "f"});

doThis({new house.bed = "dd", new house.chair="gg", new house.tv = "jjjh"});

doThis({new house.bed = "ff", new house.chair="hh", new house.tv = "hhh"});

doThis({new house.bed = "gg", new house.chair="jjj", new house.tv = "hh"});
4

3 回答 3

2

不是很明白这个问题,但是你的代码有语法错误,函数的调用应该是这样的:

doThis({bed: "a", chair: "c", house: "f"});
于 2012-07-25T07:51:09.697 回答
2

您的代码与 javascript 相差甚远,但您可以这样做:

function House(bed, chair, tv) {
    this.bed = bed;
    this.chair = chair;
    this.tv = tv;
}
doThis(new House("a", "c", "f"));
doThis(new House("dd", "gg", "asd"));
于 2012-07-25T07:52:55.093 回答
1

Like Esailija said except that doThis is not defined, so use something like this:

function House(bed,chair,tv){
    var obj = {};
    obj.bed = (bed) ? bed : "";
    obj.chair = (chair) ? chair : "";
    obj.tv = (tv) ? tv : "";
    return obj;
  }

  var myHouse = new House('water bed');
于 2012-07-25T07:57:07.633 回答