OOP in Javascript(1)

来源:互联网 发布:python spark 编辑:程序博客网 时间:2024/05/16 09:18
  • Basic ways of creating an object using javascript
  1. <script  language=javascript type="text/javascript">
  2. <!-- 
  3.     //create object using new object keyword
  4.     //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.
  5.     person=new Object();
  6.     person.name="bennyxu";
  7.     person.height=170;
  8.     person.say =function()
  9.             {
  10.                 this.state="running";
  11.                 window.alert("I'm running");
  12.             }
  13.             
  14.             
  15.     //create object using literal notation
  16.     literalObj={
  17.         property1: "hello",
  18.         property2: "Bennyxu",
  19.         property3: ["abc",2,3,4,"NEG"],
  20.         method1: function()
  21.         {
  22.             alert("method had been called " + this.property1);
  23.         }
  24.         
  25.     };
  26.     
  27.     var circle={x:0,
  28.                 y:0,
  29.                 radius:2}  //another example
  30.     //nesting is OK
  31.     var rectangle ={
  32.         upperLeft :{x:2,y:2},
  33.         lowerRight:{x:4,y:4}
  34.     }
  35.     alert("nested definition:" + "uppperLeft=" + rectangle.upperLeft.x );
  36. function Button1_onclick() {
  37.     person.say();
  38. }
  39. function Button2_onclick() {
  40.     literalObj.method1();
  41.     window.alert(literalObj.property3[2]);
  42. }
  43. //-->
  44. </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.

原创粉丝点击