Hello fellow programmers, I have taken up learning JavaScript. This syntax is pure sorcery, can someone clarify:
function CleanPet(){
alert("The pet is now clean!");
}
CleanPet.Description="Dirty Business";
The material I am reading explains that in JavaScript, functions are like any other object, but if I attach a property to a function, does this mean it is static, since I haven’t actually declared it?
Thanks for help,
I.N.
Object properties aren’t “declared” in the formal sense of using
varlike you do for variables. Given an existing objectCleanPet, you can assign properties likeCleanPet.Description(as in the question) which will create theDescriptionproperty if it doesn’t already exist, or overwrite the property if it did already exist.It is also “legal” to attempt to access object properties that you haven’t set yet, e.g.,
CleanPet.SomeOtherProperty– the resulting value will beundefined. (Not an error, though that assumesCleanPetactually is an object. IfCleanPetisnullorundefinedthenCleanPet.SomeOtherPropertywould give an error.)So regarding functions specifically, a function declaration:
…declares a single object that happens to be a function. Which means you can call it as a function
CleanPet(), but it still gets “ordinary” object behaviour such as the ability to have properties assigned.JavaScript functions are also object constructors if called with
new:In that case JS creates a new object (instance) every time you call
new CleanPet(), but theCleanPet.Descriptionproperty is not accessible viacleanPet1.Descriptionbecause it is a property of the constructor, not a property of the resultingnewinstance. So in that sense, yes, the property is “static”.