2012-07-08 54 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

原型对象可以让你保持许多对象实例共享行为都在一个地方。从那里,如果需要,可以动态更改或扩展,其效果是立即改变从原型继承的所有构造对象的能力。

还有其他不错的东西,但对我来说这是最重要的事情。