-
Basic ways of creating an object using javascript
- <script language=javascript type="text/javascript">
- <!--
- //create object using new object keyword
- //We define a custom object "person," then add to it its own properties and method afterwards. In this case, the custom method merely initializes two more properties.
- person=new Object();
- person.name="bennyxu";
- person.height=170;
- person.say =function()
- {
- this.state="running";
- window.alert("I'm running");
- }
- //create object using literal notation
- literalObj={
- property1: "hello",
- property2: "Bennyxu",
- property3: ["abc",2,3,4,"NEG"],
- method1: function()
- {
- alert("method had been called " + this.property1);
- }
- };
- var circle={x:0,
- y:0,
- radius:2} //another example
- //nesting is OK
- var rectangle ={
- upperLeft :{x:2,y:2},
- lowerRight:{x:4,y:4}
- }
- alert("nested definition:" + "uppperLeft=" + rectangle.upperLeft.x );
- function Button1_onclick() {
- person.say();
- }
- function Button2_onclick() {
- literalObj.method1();
- window.alert(literalObj.property3[2]);
- }
- //-->
- </script>
While using the new operator or literal notion to create a custom object is both
simple and logical, the biggest shortcoming is that the result is NOT reusable-
we cannot easily initialize different versions of the created object.