日期:2014-05-16  浏览次数:20410 次

javascript 类继承机制
Javascript类的继承是通过constructor和prototype来实现的

1. 定义一个形如java的person类,然后实例化和调用它的属性
  
   // Define a so called class
    var person = function() {
        this.name = "vulnerability";
        this.age = 28;
    }

    // Instantiate the class
    var p1 = new person();
    alert(p1.age);
   

   执行结果是:
   vulnerability

2. 定义一个person的子类man
  
   var man = function() {
      this.show = function() {
         alert("The man is showing himself");
      }
   }

   // Let the man extend the person
   man.prototype = p1;

   // Instantiate the man class
   var m1 = new man();
   
   // Invoke the show method
   m1.show();
   

   prototype是设置在class上而不是实例化过的对象中
   执行结果是:
   The man is showing himself

3. 拿一个未设置的属性
  
   alert(m1.name);
   

   js解析器会从首先从当前对象去找这个属性,如果没有则顺着其原型对象链(prototype chain)去找这个属性值,如果翻遍了还没有,返回undefined。
   执行结果是:
   vulnerability

4. 设置属性
  
   // Set the property of the instance of subclass
   m1.name = 'susceptibility';
 
   // Verify whether the property has been set to the instance
   alert(m1.name);

   // Verify whether the property of the instance of prototype
   // has been modified
   alert(p1.name);
   

   js在当前对象增加(更新)该属性,所以是在m1上设置。而原型对象的属性没有被改变
   执行结果是:
   susceptibility
   vulnerability

5. 设置原型对象的属性
  
   // Set the property of the prototype of man 
   man.prototype.name = 'changed value';

   // The property of the instance of subclass wouldn't be changed
   alert(m1.name);

   // The property of the prototype has been changed
   alert(p1.name);
   

   原型对象的属性被改变,但是子类对象没有。
   执行结果是:
   susceptibility
   changed value