Published on: 12/19/13 5:48 PM
Category:Javascript Tags: javascriptToday we will see more concepts on the javascript
this article is continued article of yesterday’s one Object oriented javascript
Today we will see some more concept of object oriented javascript which are essential for writing script with OOP
First we will see To instantiate or not to be instantiate
Change in object literal will affect that object accross the entire script whereas in constructor function is instantiated and then changes is made to that instant, won’t affect any other instance
for example
[code language="javascript"]<br /><br />var myObjectLiteral={<br /><br />myProperty: 'this is a property'<br /><br />}<br />//alert this property<br />alert(myObjectLiteral.myProperty);<br />//this will alert as: 'this is a property'<br />now change this property<br />myObjectLiteral.myProperty='this is new property'<br />//alert this<br />alert(myObjectLiteral.myProperty);<br />//this will alert as: 'this is new property' as we have expected<br />[/code]
Now create new variable and point towards the object, it will
have some changes
[code language="javascript"]<br />var myObjectLiteral = {<br />myProperty: 'this is my property'<br />}<br />alert(myObjectLiteral.myProperty);<br />// this will alert as: 'this is my property'<br />// take new variable now<br />var someObject = myObjectLiteral;<br />// Change property<br />myObjectLitral.myproperty = 'this is new property' ;<br />alert(someObject.myProperty);<br /><strong>//this will still alert : this is my property</strong><br />[/code]
There will not change for new variable
Now we will do same for constructor
[code language="javascript"]<br />var myObjectConstructor = function(){<br />this.myProperty = 'this is property';<br />// now instantiate constructor<br />var constOne = new myObjectConstructor();<br />// instantiate second Constructor<br />var consTwo = new myObjectConstructor();<br />// now we will alert one by one<br />alert(constOne.myProperty);<br />alert(constTwo.myProperty);<br />//this both will alert as : 'this is property'<br />}<br /><br />[/code]
so as expected this will return correct values but lets change myProperty for one of the instance
[code language="javascript"]<br />var myObjectConst = function(){<br />this.myProperty = 'this is property' ;<br />}<br />//instantiate constructor ;<br />var constOne = new myObjectConst();<br />//change in property now<br />constOne.myProperty = ' this is new ' ;<br />// instantiate second constructor<br />var constTwo = new myObjectConst();<br />//alert this<br />alert(constOne.myProperty);<br />//this will alert as 'this is new '<br />alert( constTwo.myProperty);<br />//but this will alert as: ' this is property '<br />[/code]
as you can see the differences in both of this , there is change in alerts when we change the properties of the constructor but it will not affects the previous one or entire script
Hope you understood this concept
Enjoy Javascript !!!