如何将实例化对象的属性作为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"});
答案 0 :(得分:2)
不太了解这个问题,但是你的代码包含语法错误,函数的调用应该是这样的:
doThis({bed: "a", chair: "c", house: "f"});
答案 1 :(得分: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"));
答案 2 :(得分:1)
像Esailija说的那样,除了doThis没有定义,所以使用这样的东西:
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');