什么是使用Prototype的JavaScript继承和方法调用之间的区别?

时间:2016-11-02 11:33:01

标签: javascript

以下代码使用Prototype继承,如下所示,

function Employee(name){
  var name = name;

  this.getName = function(){
    return name;
  }

  this.toString = function(){
    var str = "";
    str +=  "Name : "+this.getName()+
            "\nStreet : "+this.getStreet()+
            "\nPostal Code : "+this.getPostalCode();
    return str;
  }
}

function Address(street,postalCode){
 var street = street,
    postalCode = postalCode;

 this.getStreet = function(){               
    return street;
 };

 this.setStreet = function(str){
    street = str;               
 };

 this.getPostalCode = function(){
    return postalCode;  
 };

 this.setPostalCode = function(pc){
    postalCode = pc;
 };      
}

Employee.prototype = new Address(); // Prototype chaining

var emp1 = new Employee("Ram Patel");

emp1.setStreet("Katiar Road, Ahamadabad, Gujurat");
emp1.setPostalCode("3455454");

console.log(emp1.toString());

当上面的代码运行时,输出是

Name : Ram Patel
Street : Katiar Road, Ahamadabad, Gujurat
Postal Code : 3455454

现在使用方法调用继承,请遵循以下代码,

function Employee(name){
var name = name;

Address.call(this);

this.getName = function(){
    return name;
}

 this.toString = function(){
    var str = "";
    str +=  "Name : "+this.getName()+
            "\nStreet : "+this.getStreet()+
            "\nPostal Code : "+this.getPostalCode();
    return str;
 }
}

function Address(street,postalCode){
  var street = street,
      postalCode = postalCode;

  this.getStreet = function(){              
    return street;
  };

  this.setStreet = function(str){
    street = str;               
  };

  this.getPostalCode = function(){
    return postalCode;  
  };

  this.setPostalCode = function(pc){
    postalCode = pc;
  };         
}



var emp1 = new Employee("Peter Thiel");

emp1.setStreet("32 St. John Street, Washinton");
emp1.setPostalCode("3455242");

console.log(emp1.toString());

运行上述代码时的输出是

Name : Peter Thiel
Street : 32 St. John Street, Washinton
Postal Code : 3455242

从上面我们可以看到,这两种方式的继承在JavaScript中运行良好。

如果我使用

,那就更有意义了
Employee.prototype = new Address();

在此之上,

function Employee(name){
  var name = name;

  Address.call(this);

0 个答案:

没有答案