Showing posts with label Javascript Objects Post Thread. Show all posts
Showing posts with label Javascript Objects Post Thread. Show all posts

Friday 22 August 2008

Getting intimate with Javascript objects part #8 - The Inherited Methods and Properties

Gentle reader,
Back to the wonderful geeky world of Javascript , it has been a while since the last post in this series, I do apologise.. here is a link to the thread in case you missed the excitement that was parts 1- 7,

In this post I am going to look at the sometimes overlooked methods and properties that come as part an parcel of every object you create in JS. As I mentioned before every object you create is a "child" of the Object class and as such in inherits all the parent's methods and properties. Lets look at a few :-

toString() this method does not require any parameters and returns a string that will in some way represent the the type and value of the object. I am sorry that sounds a bit vague, but have a play with it on your own objects and you will see what I mean. You will probably get something like [object Object] which is really not that wonderful. However if you are debugging some code and for the life of you, you can'rt remember what class constructor was used to create and object you can use the toString method to test this, for example if the constructor of an object was the Array class, toString will return [object Array] as a string. This will only work for classes that are part of the JS implementation of your browser. If you try this on your own classes you will always get [object Object]. What the JS interpreter gives the JS interpreter takes away ~sigh~.

Given that it already exists you can create your own customer toString using the prototype defintion, something like this.

GirlFriend.prototype.toString = function() {
return "[The name of this girlfriend is "+ this.name+" and she has "+this.hairColor+"]";
}

Which brings me to something I should have mentioned before ,when we were discussing prototypes. You can still access the original method using the apply(0) method. for example

GirlFriend.prototyle.toString.apply(o)

[Note the 0 is a zero!]

toLocalString() is the next method and it does the exactly the same as toString() except for objects created with the ARRAY,DATE and NUMBER classes which do return values based on the Locale of the client.

valueOf() is like toString() except that it returns a primitive value that is NOT a string. Oddly since a object is an object and seldom has a primitive value this method will simply return the object. However if the object is created from the NUMBER and BOOLEAN have primitive values so these are returned when valueOf() is called.

hasOwnProperty() this can be used to test an object for the possession of a property that was NOT inherited from a parent class. It returns either true or false. For example
GirlFriend.hasOwnProperty("toString") would return false as toString is inherited from the Object Class.
Where as
GirlFriend.hasOwnProperty("hair") would return true because hair is not inherited but defined within the GirlFriend class

propertyIsEnumerable() which is a bit of a mouthful and returns true if you can put the property being tested in a for/in loop, false if not. But beware if the property is inherited then this method always returns false!

isPrototypeOf() this returns true if the object is the prototype object of the object passed to the function. Otherwise it returns false. for example

var GF = new GirlFriend();
GirlFriend.prototype.isPrototypeOf(GF) will return true
GirFriend.isPrototypeOf(GF) will return false

Anyway thats really all I have to say about Objects for the now. So this Thread is closed ;-)

Sometime soon, after my holidays I will take a wander in to the wonderfully indexed world of Arrays!

Sunday 27 July 2008

Getting intimate with Javascript objects part #7 - Really Useful Associative Arrays

Sorry about the delay getting this post to press. I have been a wee bit busy. However without further ado lets look at a javascript thingie I think is REALLY useful.

You will all be familiar now with the period operator that is used to access the properties of an object. for example myGirlFriend.hair = "Blond (Well the bits you can see)" but you cal also express this as myGirlFriend["hair"] = "Blond (well the bits you can see)".

In C,C++ and Java and object can only have a fixed number of properties that are defined at compile time. Since Javascript is "loosely" this rule is not enforced a program or function can access add or delete properties to any object. When you use the "." operator you have to use the name of the property. The text that follows the "." is not a data type so cannot be manipulated by the program.

[...Drum Roll...]

If we use the [] syntax the identifier is a string, now a string IS a javascript data type and we CAN manipulate strings ... YIPEE!

Say we had a HR data table which had an object like this
Person.Name1 = "Steve"
Person.Name2 = "John"
Person.Name3 = "Marshmallow"
Person.Name4 = "McDonagh"
and we wanted to combine all of this data into a single string for full name would do something like this
PersonFullName= Person.Name1+" "+Person.Name2+" "+Person.Name3+" "+Person.Name4
or we could do it like this

var PersonFullName="";f
or(t=1;t<5;t++)> {PersonFullName += Person["Name"+t]+" ";


This is perhaps a bit simple and not something you consider using in real life but it does demonstrate the use of the [] construct to get at information you may not know ahead of time.

Lets look at a slightly more complicated example. You have an ebusiness selling socks. You do not know ahead of each sale what size or colour or socks your users are going to buy that day.

Say a user comes along and asks for a pair scks that are Yellow and Adult size 9. You have no way using the "." operator to construct and get this information from your stock object which looks like this.

Stock.Yellow7 = 100;
Stock.Yellow8 = 15;
Stock.Yellow9 = 3;

But using the [] construct you can easily do this by concatenating the values entered by the user

alert(Stock["Yellow9"]) would result in an alert that has 3 in it.

When a object's properties are accessed in this way the object has ceased to be just an object it has become an associative array. Don't worry to much about this but you may hear the term used by some smart arse project leader like me and it pays to be up on the jargon we like to use. If you move on to PERL or PHP you will come across objects that can be accessed in this way. An PHP and PERL programmers are much nicer that those legends in their own lunchtimes Java programmers ;-)

Oh an before I forget.. like Lotusscript if you want you can use a For/In construct using the associative array method. Like this, if we wanted a total number of socks
in out Stock object.

var allsocks = 0;
for (Socks in Stock){ allsocks += Socks; }


Since we may add or delete Items from Stock, for example "Yellow Size 7" are just not selling so I give them to the charity shop and remove them from my inventory. If I use the for/in loop to get my total I do not have to change any code that may contain a line like this

allsocks = Stock.Yellow7+Stock.Yellow8+Stock.Yellow9

I use this particular trick nearly everyday and if you are going to be able to jump into the wider world of Javascript in the near future with things like xPages chances are so will you.

Next time (and hopefully very soon) I will post on the properties and methods that are inherited by ALL Javascript objects from the Object class. These methods and properties are often forgotten which is a pity because they can be quite useful!

Tuesday 15 July 2008

Getting intimate with Javascript objects part #6 - Super and Sub Classes

Okey Dokey Gentle reader - Most OO languages have an explicit concept of hierarchy within their classes. Every class can have a SUPERCLASS from which it inherits its properties and methods. Also any class can be extended or Subclassed so that the resulting SUBCLASS inherits its behaviour.

In Javascript right at the top of the object hierarchy is the Object class, all other classes both supplied and created by you the programmer are subclasses of the Object class. Or if you prefer it arse about face the Object class is the Superclass of all other objects. All classes inherit a few basic methods from the Object superclass.

Back in the Inheritance post I pointed out who object s inherit properties from the prototype object of their constructor so how can they also inherit from the Object class? A good question! Remeber the prototype is an object itself which was created from the Object class and from there it inherited the Object Class methods.

Now as was mentioned in a comment by Tim Tripcony back here The generally accepted syntax to create an empty object is now simply to = {} and [], respectively and there is no need to specify new Object(). This kinda hides the relationship from your objects to the Object() class but it is there none the less.

Ok a wee word of caution about property and method names. When a property is looked for or a method is called Javascript will look in current object first and then work its way up the inheritance "tree" searching the Object Class last, if the property or method is not found you will get an error BUT if the first property found will be the one the code uses! This in effect hides properties and methods of the same name (and case) further up the inheritance tree.

Generally Javascript does not need really complex class structures but it is possible to subclass any class. For example say we want to create a subclass of GirlFirend() called GirlFriendSize() we would do it like this first define the GirlFriendSize class

function GirlFriendSize(chest,waist,hips)
{
this.chest = chest;
this.waist = waist;
this.hips = hips;
}

Then we force its prototype to be a GirlFriend object which means that any instance of this class we create will inherit all of the properties and methods from the GirlFriend class (and for those eagle eyed amongst you the Object class as well)

GirldFriendSize.prototype = new GirlFriend()

Now we can if we wish add new methods and properties to this subclass as described in previous posts. Now if we follow this code with a

var myGirlFriend = new GirlFriendSize(36,24,36);

Since the GirlFriend class as described yesterday is

function GirlFriend()
{this.hair = "blonde";}
GirlFriend.gender = "Female";
GirlFriend.prototype.kiss = { return "Muahhhhhhhhh" };
GirlFirend.compare(gfa,gfb) {
if (gfa.hair == "blonde")

{
alert("Girlfriend A is a Blonde Bombshell")
}
if (gfb.hair == "blonde")
{
alert("Girlfriend B is a Blonde Bombshell")
}
}

The myGirlFirend instance has inherited all of the above (with the exception of the class variable which is global).

Subtle problem time ... since GirlFriendSize.prototype points at an object of our own creation we have overwritten the prototype object provided by javascript.

"So what?" i hear you ask, well the constructor property get all snafu'ed. The constructor property is one of those things inherited from the Object superclass. This property holds the constructor function that created the object, which is not as you might expect GirlFriendSize but is GirlFriend. Now it depends if you are going to use the constructor property in your code as to whether you need to correct this. For completeness this "wrinkle" can be got around by setting constructor explicitly like this

GirlFriendSize.prototype.constructor = GirlFriendSize;

Oh a word of warning you can't do this with Javascript 1.1 co the constructor property is read-only ... b**tard!

Tomorrow a much more exciting and very useful (well for me anyway) Associative Arrays ... yummy!

Monday 14 July 2008

Getting intimate with Javascript objects part #5 - Instance and Class Methods and Properties

A while ago I started this thread and in the last post i said that "...tomorrow I will look at Instance Properties,Instance Methods,Class properties and Class methods" Well my only excuse is that I didn't tell you which tomorrow it was going to be.

Apologies for the hiatus, I was caught up in other things.... anyway on with the show.

Instance properties
Every objedct has its own separate copies of its instance properties. Lets say I have this code

var StevesGirlfriend = new GirlFriend();
var NiallsGirlFirend = new GirlFriend();
var PaulsGirlFriend = new GirlFriend()'

StevesGirlFriend.hair = "Blonde";
NiallsGirlFriend.hair = "Brunette";
PaulsGirlFriend.hair = "Ginger";

I have 3 objects all with an instance property called hair and each object has its own instance property called hair. By default any object property in Javascript is an instance property, however if we are going to be all anal about the Object Orientedness we have to say that instance properties are those that are created or initialized inside an object by the constructor method.

Instance Methods
Instance Methods differ from Instance Properties only in that they contain methods (or if you prefer "code to do shit with") rather than a data value. Like the Instance property each object has its own private copy of the method. So when you run this code

var StevesGirlfriend = new GirlFriend();
var NiallsGirlFirend = new GirlFriend();
var PaulsGirlFriend = new GirlFriend()'

StevesGirlFriend.hair = "Blonde";
NiallsGirlFriend.hair = "Brunette";
PaulsGirlFriend.hair = "Ginger";

StevesGirlFriend.kiss("no tongues");


The method kiss("no tongues") is run only with the StevesGirlFriend object and is not run for any of the other objects. Easy init? :-)

Class Properties

Now pay close attention ... this is where it gets a little freaky ...
Class Properties are properties that are aassociated with the class that defines the object rather than any object that is created from that class, no matter how many that may be.

We do this by creating and initializing the property in the constructor method ... for example

GirlFriend.gender = "Female";

The code above is the constructor method for the GirlFriend object. When new Girlfriend() is called it is created and the class property GirlFriend.gender = "Female" Now whenever the gender of the object is accesses the Class Property is retrieved and not the Instance Property

Class Methods

A class method is a method associated with a class rather than an instance of a class.

If you have used Javascript before you will have come across these already, for example the Date.parse() method is always invoked through the class constructor method rather than through a particular instance of the class.

**WARNING**
because class methods are bound to the class and not an instance of the class class methods cannot use the this keyword!

Putting all that together

OK

function GirlFriend()
{
// This is an Instance variable
this.hair = "blonde";
}
// This is a Class Property
GirlFriend.gender = "Female";

// This is a function and as it is a prototype that makes it an Instance Method
GirlFriend.prototype.kiss = { return "Muahhhhhhhhh" };

// This function compares two GirlFriend objects and makes a sexist comment
// Since this function has to compare two instances of the same class it doesnt
// make sense to have it associated with each instance. So I make it a class method.
GirlFirend.compare(gfa,gfb) {
if (gfa.hair == "blonde")

{
alert("Girlfriend A is a Blonde Bombshell")
}
if (gfb.hair == "blonde")
{
alert("Girlfriend B is a Blonde Bombshell")
}
}

Hopefully that should make sense :-)

Next post will be on Superclasses and Subclasses

Tuesday 24 June 2008

Getting intimate with Javascript objects part #4 - Orienting your Objects

Ah Hah! Now the going gets interesting - Object-Oriented Javascript!

You would think that a language that doesn't have a formal class would have it hard playing with the classic object-oriented languages like C++, Java and (lord help me) C#. Object-Oriented Geeks can be a funny lot and they would have you believe that a "real" object oriented language is strongly typed and supports class based inheritance. As an example of this kind of delusion I give you Ben Poole who spends all day ferkling with java in eclipse and is proud to wave goodbye to the last remnants of his street cred by calmly stating in broad daylight and SOBER, that Kajagoogoo are cool ... need I say more? (actually Ben is a lovely chap who has no problem with javascript but he does spend WAY to long Ferkling!)

As I have shown in the last couple of posts. Javascript makes use of objects, has its own prototype based inheritance and as a result can stand up proud as a OO language along side Java (no relation) and C++. If the other Object Oriented languages want to look down their noses at Javascript well let them, they are no better than they should be anyway!

OK for those of you that are unfamiliar with Object Oriented terminology (I couldnt be arsed typing Object-Oriented all the time so it will from now on be shorted to OO) here is a quick summary. An Object is a data structure that contains various bits of named data called properties and may contain various functions called methods that do things.

Objects are our friends, love them, hug them and call them George.

Why? Because they group related data and functions into a convenient package which naturally increases modularity and resuability of code. YIPPEE! Being a professionally lazy person I don't like working hard and constantly writing the same bit of code, to be frank, skunders my pish, anything that means I have to type less is an A+, Gold Star, goto the top of the class sort of thing to me! Not that has anything to do with OO programming of course thats just me being lazy.

In Javascript we can have any number of methods and properties and dynamically add them to our objects basically when we need them. In Java and C++ because they are "strictly typed" you can't do this (well not easily) that's why they are called strict. Also each object has a predefined set of properties (called fields) and each property has a predefined type. These definitions are made in the CLASS an object in Java or C++ is defined by its CLASS a bit like the late 1950's in England sorta like this ...waits for the video to be consumed... whilst javascript does not have a rigid class structure it can do most of the things the "proper" OO languages can so we will not get a sore in our neck looking up at Java and C++!

In any OO language there may be many objects created from the same class. When often say that an object is an instance of the class and if we are being really geeky we don't create an object we instantiate it. So if you don't want to be laughed at but ubergeeks don't say "I have just made a HarveyWallBanger doobrydo from my Cocktail thingy" say "I have instantiated a HarveyWallBanger object from my Cocktail class" it will make you look way cool!

In Java it is a common convention to name classes with a capital letter and to name objects with lowercase letters. This helps keep classes and objects distinct in code. This is a useful thing to do in Javascript as well.

That's enough for today.. tomorrow I will continue with how Javascript copes with the idea of Instance Properties,Instance Methods,Class properties and Class methods.

Getting intimate with Javascript objects part #3 - prototypes and verrucaes

Gentle reader ,
have you got your geek waders on because the Javascript puddle we are about to paddle in can get quite deep? Today I am poking "Prototyping" in the eye with a stick and then running away in the hope that you can get an inkling about how Prototyping works so that properties and methods can be "inherited".

Prototyping is a prebuilt keyword that simplifies the process of adding custom properties/ methods to all instances of an object.

In JavaScript, you're allowed to add custom properties to both prebuilt and custom objects. Here's an
example of each:

//adding a custom property to a prebuilt object
var MySexyGirlfirend =new Image()
MySexyGirfriend.vitalstatistics="36:24:36"

//adding a custom property to the custom object verrucae
//First, create the custom object "verrcuae"
function verrucae() {}
var ItchyLeftFoot=new verrucae();
ItchyLeftFoot.nodules = 4;


A custom property added this way only exists for that instance of the object. If I were to spit out another instance of verrucae(), called ItchyRightFoot, for example, ItchRightCircle.nodules would by default return "undefined" until I go over the process again of first defining ItchyRightFoot.nodules, as with ItchyLeftFoot example above.

There are times when you'll want to add a custom property that's only reflected on a particular instance of an object, and times, when you just wished all instances of the object would recognize the custom property. For example, all verrucae objects have a default nodule count of 4, so it's reasonable to assume you'd like the custom property "nodules" to added to the verrucae in a way so that it's default across all instances of the verrucae object that you create. That's where the prototype methodology comes in.

The prototype methodology is here to help when you wish to quickly add a custom property or method to an object that will be reflected on all instances of it. To use it simply reference the keyword "prototype" on the object before adding the custom property to it, and this property is instantly attached to all instances of the object.
Consider this :

function verrucae() {}
verrucae.prototype.nodules=4;
var ItchyLeftFoot = new verrucae();
var ItchyRightFoot = new verrucae();

On the second line I added a prototype property to the object. So ItchyLeftFoot and ItchyRightFoot both have a property of .nodules = 4 without having to manually set it.

** Updated **
There is an important thing to take note at this point in our wander. While you are free to use the prototype object on any custom objects, this is NOT the case with some of the prebuilt objects. Whilst those lovely people at Mozilla allow you to prototype most if not all objects IE allows you to "prototype" those objects that can be created with the "new" keyword, such as Image(), String(), Date() ,Object() , Array(). So if your IE users start complaining that they are getting "Object does not support this method" error messages and your Firefox users are OK .. you will know what the problem is.

.o0(yes indeed I do know what the problem is.. IE is a heap of POO!.. short simple and elegant summation I think)

The prototype object can also help you quickly add a custom method to an object that is reflected on all instances of it. To do so, simply create the object method as usual, but when attaching it to the object (you guessed it), use "prototype" beforehand. Let's extend our verrucae object so it contains a default method that does something simple, like alert the discomfort of the owner.

//First, create the custom object
function verrucae(){}
verrucae.prototype.nodule=4;
//Then create the function you want to attach to the object
function v_ouch ({ alert('OUCH my verrucae has '+this.nodules+" nodules and it is very sore!')}
verrucae.prototype.ouch= v_ouch


Now, all instances of the verrucae object contain a ouch() method!

As mentioned before, the prototype methodology can be used on pre-built JavaScript objects but ONLY those created with the "new " keyword. Let's see an interesting example on how to extend the prebuilt String() object of JavaScript to include a method that writes any string as pig latin when called upon:

function v_pigMe()
{

var word = this.split(" ")
outp = ""
for (i = 0; i < word.length; i++)
{
thisword = word [i]
alert(thisword)
outp = outp + thisword.substring (1, thisword.length) + thisword.substring(0,1) + "ay "
}
alert(outp)
}
//Attach custom method to string object
String.prototype.pigMe=v_pigMe;

The above code may not look like much, but it just added a whole new functionality to the default string object - the ability to output any text in pig latin. Surely a bonus in this modern multicultural world?

** Comming Soon ** Fooling JS into the notion that it has classes.

Monday 23 June 2008

Getting intimate with Javascript objects part #2 - the modus operandi of methods

OK Gentle reader here we go with part 2 of this thread and tonight we will a closer look at methods. Now this has NOTHING to do with the way an actor analyzes deeply the motivations and emotions of the character in order to personify him or her with psychological realism and emotional authenticity (... och bless isnt he such a LOVEIEE!...) having said that Robert De Niro as Travis Bickle, need I say more?

... I digress. JS Objects and their methods. Put bluntly methods do things. They are just like ordinary JS functions except they are invoked through the object they are associated with.

Yesterday is said "You are not constrained when it comes to the type of Properties you can store in an object, any of the JS data types can be stored as a property in an object" ... remember? Well the other thing you can store as a data value is a function.
"No" i hear you cry "how do they do that?"
And I would reply, were you here "There were 2 people who knew, God and me, and now only God knows" so basically who cares, functions can be stored in the same way as data values! YIPEE! Ok so how do I "do" a method. Well lets look at this object.

var MyDingALing - new Object();
MyDingALing.LittleBittyBoy = true;
MyDingALing.SilverBells = "On String";

After this code has run in the memory of the browser is an object called MyDingALing
which has two properties LittleBittyBoy which has a boolean value of true and SilverBells which has a value of "On String" lets say we want to add a method to this object we do this

var MyDingALing - new Object();
MyDingALing.LittleBittyBoy = true;
MyDingALing.SilverBells = "On String";
MyDingALing.playWith = function() { alert("Ooh you naughty BOY!") }

To invoke this all you need to do is this

MyDingALong.playWith()
Oddly this code actually works click below



Now methods have one very very important property and it is this. No really it is this. Yes this.
Sorry about that... geek pun.The this keyword in JS is the hook by which we can refer to the object that contains the method we are processing. Consider this

....(sorry did it again but this time by accident :-) )

var MyDingALing - new Object();
MyDingALing.LittleBittyBoy = true;
MyDingALing.SilverBells = "On String";
MyDingALing.playWith = function() { msgText = this.LittleBittyBoy?" are ":" are not ";

alert("You "+msgText+" in possession of the correct Little-Bitty-ness!")
}

this.LittleBittyBoy refers to the value stored in that property of object that invokes the
playWith() method. For those of you going WTF is something?this:that; Well it is a short hand way of doing an if .. then.. else and it works like this
[test of something that will evaluate to true or false]?[true result]:[false result];

OK?
So if I set the LittleBittyBoy property to true what happens


and if I set the LittleBittyBoy property to false what happens


Exciting init?

Anyway that is how you DO JS methods on an object.

Tomorrow's wander will be around the busty statues at the bottom of the JS garden that are Prototypes and Inheritance.

Sunday 22 June 2008

Getting intimate with Javascript objects part #1


Gentle reader,
This evening I am going to start a series of posts where I will have a little poke around JavaScript objects and Object-Oritented JS in my own weird manner. So for my non-geek readers it is probably best that you leave now - no one will think the worse of you if you do:-)

OK let the geeky fiddling and poking begin!

Objects are composite data types. There we go, RGQ (Required Geekiness Quotient) achieved, I managed to get the word "composite" shoe-horned into the first sentence! Mind you in the context of JS objects it is also very apt because a JS object is a composite object that clumps together lots of related values and functions into one unordered, named collection.

A. Creating Objects

Objects can be created with the new operator followed by the constructor function for the object

The most basic of these would be
var MyThing = new Object();
This object exists at the same usefulness quantum level as a "glass hammer" or a "chocolate BBQ" as it contains no properties and has no methods. Think of MyThing as the Paris Hilton of JS variables. Rather than an "it-girl" it is a "it-var", superficially interesting enough to take on one date, but the resulting sex tape would be crap.

Ohh slipped in some more Object Jargon there ... just so you know

The Values stored in an Object are called Properties
The Functions stored in an Object are called Methods

Moving quickly on, you are bound to have used constructor functions before, like these

var MyDate = new Date();
or
var MyNextHangover = new Date(2009,01,01)
are examples of creating an object that represents a date and time. You can do lots of interesting things with the JS date object which you can explore here.

BUT!!!!! just to make JS interesting ... you don't have to create an object using a constructor you can use the Object Literal method to create and initialize new objects. An Object literal is a comma-separated list of property-name: value pairs enclosed in curly brackets (or braces if you have to call them that) for example
var MyCockTail = {
name: "Sex on the beach",
price: 3.50,
type: "Fruity",
glass: "Highball",
garnish: "Lime Wedge"
}
Would create a JS object that holds the details of a particularly tasty if oddly named cocktail.

You are not constrained when it comes to the type of Properties you can store in an object, any of the JS data types can be stored as a property in an object. I emboldened that because it is important and I WILL be mentioning it again so it is best that you make a "note to self" now .. s'ok I will wait here while you do it

[..waits...]

For example
var MyCockTail = {
name: "Sex on the beach",
price: 3.50,
type: "Fruity",
glass: "Highball",
garnish: "Lime Wedge",
mix: {
shotA: "2 x Vodka",
shotB: "1 x Peach schnapps",
shotC: "3 x Orange Juice",
shotD: "3 x Cranberry Juice"
}
}
This is the same as the previous example except I have added a new property to the object named mix which is an object itself containing the properties shotA,shotB,shotC and shotD.

B. Accessing ,Setting Object Properties and deleting a Property when you are done

OK got that now how do I access these things in my code. well that is dead easy use the period operator, period. .o0(oh the savage wit!) Seriously you use the . character to access the value of an objects property. For example using the MyCockTail object we created above we can pull out the name thusly :

MyCockTail.name
or
MyCockTail.price
or
MyCockTail.mix.shotA

So we could have a piece of JS that goes like this

alert("You have selected "+MyCockTail.name+" which is a "+MyCockTail.type+" drink")

Easy init? :-)

But what happens if if want to change the value of a property in code? That is easy, just set it the same way you would if it was an ordinary variable. like this

MyCockTail.name = "Entirely innocent frolic on the beach";

Would make the name of the cocktail in the example above acceptable at a church social.

"But...", I hear the brighter of you ask "..what happens if i try to access a property that either doesn't exist or has yet to be set?" Well if you do this, a large boxing glove will materialize from the screen and get all Evander Holyfield with your nose ... I jest but dont' you wish you could do that? ... anyway all that happens is that the you end up retrieving the undefined value. For example

alert(MyCockTail.hasUmbrella)

would result in the alert dialog appearing with undefined in it like this


"OK", the smart arse in the audience says "How do I delete a property?"

I look smug and reply "like this...."

delete MyCockTail.name

but be careful this does not just set the value of MyCockTail.name to undefined. It deletes the entire property from the object. It is gone completely!

Ok that is enough for today ... in the next posts in this series I will look in more detail at rolling your own constructor method ,prototypes and inheritance, and how to fool JS into the notion that it has formal classes.

Disqus for Domi-No-Yes-Maybe