Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/user-interface/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何扩展javascript类_Javascript_Class_Inheritance - Fatal编程技术网

如何扩展javascript类

如何扩展javascript类,javascript,class,inheritance,Javascript,Class,Inheritance,为什么子类没有echo()方法 在Javascript中如何从父类继承?您需要将子类的原型设置为父类 function Parent() { this.name = 'abc'; } Parent.prototype.echo = function () { alert(this.name); } function Child() { } Child.prototype = new Parent() var x = new Child(); x.echo(); 我假

为什么子类没有echo()方法


在Javascript中如何从父类继承?

您需要将
子类的原型设置为
父类

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

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

function Child() {

}

Child.prototype = new Parent()

var x = new Child();

x.echo();

我假设您使用jQuery。jQuery扩展系统使用对象,而不是“类”,请参见:

  • javascript中没有“类”,只有对象和原型继承
  • 父、子不是类,它们是函数(以及对象)
  • 在子对象中,“this”指的是全局对象(“浏览器的窗口”)
  • 使用
    Child.prototype=new Parent()

这是否使用jQuery?“普通”javascript中的子类不是这样工作的。在其中抛出jQuery
$.extend
只会让一切都变得混乱。
function Parent() {
    this.name = 'abc';
}

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

function Child() {

}

Child.prototype = new Parent()

var x = new Child();

x.echo();