2012-07-08 73 views
1

我試圖在JavaScript中學習OO技術。大多數網站使用原型繼承。爲什麼在javascript中繼承的原型是必需的

但是,我想了解爲什麼以下是壞的(現在仍然能達到什麼原型繼承可以做):

 //create parent class 
    var Person = function (vId, vName) { 
     this.Id = vId; 
     this.Name = vName; 

     this.Display = function() { 
      alert("Id=" + this.Id); 
     } 
    }; 

    //create new class 
    var Emp = function (vId, vName, vOfficeMail) { 
     Person.call(this, vId, vName) 
     this.OfficeEmail = vOfficeMail; 

     this.Display = function() { 
      alert("Id=" + this.Id + ", OfficeMail=" + this.OfficeEmail); 
     } 
    }; 

    //create instance of child class 
    var oEmp = new Emp(1001, "Scott", "[email protected]"); //using Child's constructor 
    //call display method in child class 
    oEmp.Display(); 

    //create instance of parent class 
    var oPerson = new Person(1002, "Smith"); //using Parent's constructor 
    //call display method in parent class 
    oPerson.Display(); 
+2

[*原型繼承*](http://en.wikipedia.org/wiki/Prototype-based_programming )是JavaScript知道的唯一繼承。 – Bergi 2012-07-08 20:21:50

回答

4

這是我認爲最重要的,也是一個簡單的解釋。

此代碼將創建一次函數爲每個對象:

this.Display = function() { 
    alert("Id=" + this.Id); 
} 

使用原型的功能,而不是隻創建一次,並且適用於所有該類型的對象。浪費更少的內存和更少的CPU功耗。

此代碼將顯示什麼我談論:

var Person = function (vId, vName) { 
     this.Id = vId; 
     this.Name = vName; 

     this.Display = function() { 
      alert("Id=" + this.Id); 
     } 
    }; 

    var a = new Person(1, 2); 
    var b = new Person(3, 4); 

    var instanceEqual = (a.Display == b.Display);// false 
    alert("Instance functions equal: " + instanceEqual); 

    Person.prototype.Display2 = function() { 
      alert("Id=" + this.Id); 
     } 

    var prototypeEqual = (a.Display2 == b.Display2);// true 
    alert("Prototype functions equal: " + prototypeEqual); 

的jsfiddle:http://jsfiddle.net/nPnrk/

2

原型對象可以讓你保持許多對象實例共享行爲都在一個地方。從那裏,如果需要,可以動態更改或擴展,其效果是立即改變從原型繼承的所有構造對象的能力。

還有其他不錯的東西,但對我來說這是最重要的事情。