《悟透JavaScript》学习札记八之构造对象

来源:互联网 发布:php while sleep 编辑:程序博客网 时间:2024/05/01 11:47
 

<script type="text/javascript">
   function MyFunc(){}; // 定义一个空函数
   var obj1 = new MyFunc();
   var obj2 = new MyFunc; // 函数可以没有括号,但仍将调用该函数!

   // 还可以用下面的等价形式
   function MyFunc(){};
   var obj = {}; // 创建一个对象
   MyFunc.call(obj); // 将obj对象作为this指针调用MyFunc函数

   function Person(name) //带参数的构造函数
   {
    this.name = name; // 定义并初始化name属性
    this.SayHello = function () // 定义对象方法SayHello
    {
     alert("Hello, I'm " + this.name);
    };
   };

   function Employee(name, salary) // 子构造函数
   {
    Person.call(this, name); // 调用父构造函数
    this.salary = salary;
    this.ShowSalary = function ()
    {
     alert(this.name + " $ " + this.salary);
    };

   };

   var BillGates = new Person("Bill Gates");
   var Kevin = new Person("Kevin");
   var SteveJobs = new Employee("Steve Jobs", 5000);
   BillGates.SayHello(); // output: I'm Bill Gates
   SteveJobs.SayHello(); // output: I'm Steve Jobs
   SteveJobs.ShowSalary(); // output: Steve Jobs $ 5000

   alert(BillGates.constructor == Person); // true
   alert(SteveJobs.constructor == Employee); // true

   alert(BillGates.SayHello == SteveJobs.SayHello);
   alert(BillGates.SayHello == Kevin.SayHello);
   // false, 函数即对象。同一类的对象各有一份方法代码,显然是种浪费。
  </script>
  <script type="text/javascript">


  // 以下通过定义全局函数实现方法共享
  function SayHello() // 定义全局SayHello函数
  {
   alert("Hello, I'm " + this.name);
  };

  function Person(name)
  {
   this.name = name;
   this.SayHello = SayHello;
  };

  var p1 = new Person("Kevin");
  var p2 = new Person("Mike");

  alert(p1.SayHello == p2.SayHello); // true
  </script>

原创粉丝点击