2010-09-18 68 views
2

爲什麼Child類沒有echo()方法?如何擴展javascript類

Parent = function(){ 
    this.name = 'abc'; 
} 

Parent.prototype.echo = function(){ 
    alert(this.name); 
} 

Child = function(){ 
    $.extend(this, Parent); 
} 

var x = new Child(); 

x.echo(); 

我該怎麼做才能從Javascript中的父類繼承?

+1

難道這使用jQuery? '普通'JavaScript中的子類不能以這種方式工作。 – 2010-09-18 19:33:14

+0

在那裏拋出jQuery'$ .extend'只是混淆了一切。 – 2010-09-18 19:34:54

回答

7

您需要將Child的原型設置爲Parent

function Parent() { 
    this.name = 'abc'; 
} 

Parent.prototype.echo = function() { 
    alert(this.name); 
} 

function Child() { 

} 

Child.prototype = new Parent() 

var x = new Child(); 

x.echo(); 
+0

是的,在這種情況下,不會使用jQuery – 2010-09-18 19:36:21

0
  • 有沒有「階級」在JavaScript中,只有對象和原型繼承
  • 父,子不類,它們的功能(如以及對象)
  • 在兒童,「這」指的是全局對象(「窗口」的瀏覽器)
  • 使用Child.prototype = new Parent()