[SOLVED] Seeking info concerning JS functions

So, I created a function:

var setObjAttToVal(obj,att,val){
    obj[att] = val;
};

Now, let's say game.player is an in-game object, and game.player.name is a string.

I can do this:

setObjectAttToVal(game.player,name,"McLovin")

...but I also wish to be able to do this:

game.player.setObjectAttToVal(name,"McLovin")

It seems like someone (possibly mrangel?) once showed me how to set functions up to work this way. I've searched the forums (and the Google) for quite a while, but to no avail.

Do I just have to set it up like this? (On each object?)

game.player.setObjectAttToVal = function(att,val){ this[att] = val; }

...or is there a way to add that function to the prototype object (or something)?

Not a huge deal. It just seems like someone once told me how to do this. If it can be done, it would make my code nicer.


NOTE: This is not an actual function I wish to use. Just an example.


I can do this:
setObjectAttToVal(game.player,name,"McLovin")

Pedantry, sorry. But I think you want "name" there.

Do I just have to set it up like this? (On each object?)

That works :)
If the in-game objects are all the same class (I haven't looked at the codebase in a long time) then I think it would be:

ClassName.prototype.setObjectAttToVal = function(att,val){ this[att] = val; };

Aha!

Thank you!

Object.prototype.isWearing = function(obj){ return isWearing(this,obj)};

Wow!

Now I could just set it up this way.

Object.prototype.isWearing = function(obj){ return (obj.getWorn() && obj.loc===this.name)};;

Thanks again, mrangel!


And like that, you can even do:
document.isWearing(w.headband)

OK, that's a silly thing to do. But I don't think it would cause any issues.


This topic is now closed. Topics are closed after 60 days of inactivity.

Support

Forums