PDA

View Full Version : ByRef?



TNO
03-17-2008, 03:03 AM
I don't know a better way to say than that, how would I go about passing a reference to an object instead of the object itself (like the ByRef statement in VB)?

I have the following object as an example:



var myObject= function(){
var Stage = [
{id:"E1",type:"Actor",name:"bob"},
{id:"E2",type:"Actor",name:"fred"},
{id:"E3",type:"Spout",name:"krusty"},
];

return{
$ : function(id){
//???
},
addObject : function(obj){

},
init : function(id){

},
render : function(){

}
}
}();



I would like to do the following:

myObject.$("E1").name = "Michael";

Any ideas on how to refer to alter the object in the array directly vice a copy?

Trinithis
03-17-2008, 07:15 AM
function Character(id, type, name) {
this.id = id;
this.type = type;
this.name = name;
}

var obj = (function() {
var stage = [
new Character("E1", "Actor", "bob"),
new Character("E2", "Actor", "fred"),
new Character("E3", "Spout", "krusty")
];
return {
$: function(id) {
for(var i = stage.length - 1; i >= 0; --i)
if(stage[i].id == id)
return stage[i];
return null;
},
addObject: function(obj) {},
init: function(id) {},
render: function() {}
};
})();

You might want to consider using an identifier other than $.

TNO
03-17-2008, 09:36 AM
Sorry, that format destroys the namespace design. Only 1 global variable allowed in my situation. I'm just going to stick to this design. Its not as direct as I want, but it'll do:



var myObject= function(){
var Stage = [
{id:"E1",type:"Actor",name:"bob"},
{id:"E2",type:"Actor",name:"fred"},
{id:"E3",type:"Spout",name:"krusty"},
];

return{
getAttribute : function(id,attrib){
for(var i in Stage){
if(Stage[i]["id"] === id){
return Stage[i][attrib];
}
};
},
setAttribute : function(id,attrib,value){
for(var i in Stage){
if(Stage[i]["id"] === id){
Stage[i][attrib] = value;
}
};
}
}
}();

liorean
03-17-2008, 02:22 PM
Sorry, that format destroys the namespace design. Only 1 global variable allowed in my situation.You can still do it the way Trinithis suggests. Just modify the code this little bit:

function Character(id, type, name) {
this.id = id;
this.type = type;
this.name = name;
}

var obj = (function() {
function Character(id, type, name) {
this.id = id;
this.type = type;
this.name = name;
}

var stage = [
new Character("E1", "Actor", "bob"),
new Character("E2", "Actor", "fred"),
new Character("E3", "Spout", "krusty")
];

return {
$: function(id) {
for(var i = stage.length - 1; i >= 0; --i)
if(stage[i].id == id)
return stage[i];
return null;
},
addObject: function(obj) {},
init: function(id) {},
render: function() {}
};
})();Then if you want to use getters and setters but disallow direct unchecked setting of the value, you can add them on the Character.prototype object.