views:

58

answers:

3

Why Child class doesn't have echo() method?

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

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

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

var x = new Child();

x.echo();

What should I do to inherit from parent class in Javascript?

+5  A: 

You need to set the prototype of Child to 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();
ChaosPandion
yes, lots easier to _not_ use jQuery for this situation
Simon Groenewolt
A: 

I'm assuming you use jQuery. The jQuery extend system uses objects, not 'classes', see: http://api.jquery.com/jQuery.extend/

Simon Groenewolt
A: 
  • There are no 'classes' in javascript, only objects and prototypal inheritance
  • Parent, Child are not classes, they are functions(as well as objects)
  • Within Child, 'this' refers to the global object('window' for browsers)
  • use Child.prototype = new Parent()
letronje