OOP in Javascript(1)

本文介绍了使用JavaScript创建对象的基本方法,包括使用new关键字定义自定义对象并添加属性和方法,以及使用对象字面量表示法创建对象。此外还展示了如何通过字面量表示法嵌套定义对象。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

  • 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.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值