经典与原型......它们如何如此不同?

ekh*_*led 1 javascript inheritance prototype class object

例如在PHP中

class foo{
  function foo($name){ //constructor
    $this->name=$name;
  }
  function sayMyName(){
     return $this->name;
  }
}
class bar extends foo{
  function sayMyName(){
     return "subclassed ".$this->name;
  }
}
Run Code Online (Sandbox Code Playgroud)

在JS中

function foo(name){
  this.name=name;
}
foo.prototype.sayMyName=function(){return this.name};

function bar(){}

bar.prototype=new foo();
bar.prototype.sayMyName=function(){return "subclassed "+this.name};
Run Code Online (Sandbox Code Playgroud)

我是javascript的新手,所以请赐教,不是它们功能相同,还是我错过了一些巨大的东西?
如果它们是相同的,那么经典与原型有何不同?

提前致谢...

Mar*_*ius 6

在JavaScript中,您可以在程序运行时更改继承,这是您在经典编程中无法做到的.例如:

function foo(name){
  this.name=name;
}
foo.prototype.sayMyName=function(){return this.name};

function foo2(name){
  this.name = name;
}
foo2.prototype.sayMyName = function(){return "My name is "+this.name;};

function bar(){}

bar.prototype = new foo();
var myBar = new bar();
myBar.name = "Marius";
alert(myBar.sayMyName());

bar.prototype = new foo2();
var myBar2 = new bar();
myBar2.name = "Marius";
alert(myBar2.sayMyName());
Run Code Online (Sandbox Code Playgroud)