May 202012
 
Share...Tweet about this on TwitterShare on FacebookShare on Google+Share on StumbleUponShare on LinkedInPin on PinterestShare on TumblrShare on RedditDigg this

This post is a continuation of the earlier post Object Oriented Javascript – Object Creation, on which are explained the different ways of creating objects in javascript.

With this post I would like to explain the other possibilities javascript offers when it comes to the method and properties creation.

Adding and deleting methods and properties

Javascript is so flexible that we are able to attach and detach properties and methods even after the object creation. This makes the language extremely powerful as it offers us a possibility of modifying the behaviour of an object at runtime.

Lets consider the following example:
[javascript]

[/javascript]

as you have seen, adding the age property is as simple as declaring person.age and assigning a value. The same happens with the method declaration person.SaySomething that now points to the anonymous function that in our case simply prints “Hello” in the console.

Deleting a property from an object

Javascript offers another very interesting operation which is the possibility of deleting/detaching a property or a method from an already defined object. We can do this by using the delete keyword as follows:

[javascript]

[/javascript]

Determine Whether an Object Has a Property

Another very handy operation that Javascript offers is the possibility of querying an already defined object whether it contains a property or a method. This could be considered some sort of Javascript “reflection” mechanism, as we know it in C#.
In order to determine if an object has a property or a method the in operation has to be used. Obviously we may use this feature to check if the property has been defined before attaching it to the object.

[javascript]

[/javascript]

Read/Write properties

Every time we declare a property, the javascript runtime automatically creates a getter and a setter, which means that we may read and/or assign values. There are mainly two ways of achieving this. By using the “standard” notation or the litteral notation as shown in the example below:

[javascript]

[/javascript]

    Share...Tweet about this on TwitterShare on FacebookShare on Google+Share on StumbleUponShare on LinkedInPin on PinterestShare on TumblrShare on RedditDigg this

    I'm a Software Developer and Solution Architect interested in Software Development, Object-Oriented Design and Software Architecture all this especially bound to the Microsoft.NET platform.Feel free to contact me or know more in the about section

    Leave a Reply

    longton@mailxu.com champine232@mailxu.com