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();
开发者_如何学Go
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()
精彩评论