简体   繁体   中英

how to extend javascript classes

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?

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();

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

  • 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()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM