JavaScript对象子类 [英] JavaScript object sub-class

查看:96
本文介绍了JavaScript对象子类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想创建继承自超类A的子类B.
我的代码在这里:

I want to create sub-class B that inherits from super-class A. my code here:

function A(){
    this.x = 1;
}

B.prototype = new A;
function B(){
    A.call(this);
    this.y = 2;
}
b = new B;
Console.log(b.x + " " + b.y );

运行时,显示B未定义。

when run it,it show B is undefined.

推荐答案

在尝试访问其原型之前,必须先定义B构造函数:

You must define the B constructor function before trying to access its prototype:

function A(){
  this.x = 1;
}

function B(){
  A.call(this);
  this.y = 2;
}

B.prototype = new A;

b = new B;
console.log(b.x + " " + b.y );  // outputs "1 2"

这篇关于JavaScript对象子类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆