js里的原型继承问题

码出春天 2015-08-10 05:03:45
function A(x){
this.x=x;
}

A.prototype.getx=function(){
return this.x;
}

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

B.prototype=new A();/*疑问*/
var b=new B(1,2);
alert(b.getx());


上面的代码是js中实现继承的一种常用方式,问题是我标明疑问的那一行为什么不可以写成
B.prototype=A.prototype;

这样写也能让B的实例继承A原型中的属性吧,两种写法区别在哪呢?球指教,先谢了
...全文
96 4 打赏 收藏 转发到动态 举报
写回复
用AI写文章
4 条回复
切换为时间正序
请发表友善的回复…
发表回复
似梦飞花 2015-08-12
  • 打赏
  • 举报
回复
反向继承 一个错误的说法 但你可以查下
豪情 2015-08-12
  • 打赏
  • 举报
回复
把注释打开关闭看看:

function A(x){
    this.x=x;
    this.method = function(){
        console.log('method');
    }
}
A.prototype.getx=function(){
    return this.x;
}
function B(x,y){
    this.y=y;
//        A.call(this,x);
}
//    B.prototype=new A();/*疑问*/
B.prototype= A.prototype;
var b=new B(1,2);
console.log(b.getx());
console.log(b.method());
KK3K2005 2015-08-11
  • 打赏
  • 举报
回复
假定 还有个c 要继承b 那么 B.prototype=A.prototype; C.prototype=B.prototype; 你觉得 是继承关系吗
sydhr_1994 2015-08-11
  • 打赏
  • 举报
回复
你这么写有大问题,JS中的对象赋值是引用传递啊。 你这样改B的prototype就把A的prototype改了

87,901

社区成员

发帖
与我相关
我的任务
社区描述
Web 开发 JavaScript
社区管理员
  • JavaScript
  • 无·法
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧