JavaScript继承(设置原型内部)失败

时间:2014-09-20 22:37:40

标签: javascript ecmascript-5

我尝试在构造函数中设置prototype属性,但它不起作用,但为什么呢?如果我将属性设置为外部,一切正常。谢谢!

var a=function(){
    this.x=1;
}

var b=function(){
    this.prototype=new a();

    this.getX=function(){
        return this.x;
    }
}

alert(b.prototype);

var test=new b();
alert(test.getX());

1 个答案:

答案 0 :(得分:0)

发生的事情是你正在为" b"的每个实例创建一个公共财产。叫做原型'。不是要继承的实际原型对象。

var a=function(){
  this.x=1;
}

var b=function(){

this.getX=function(){
    return this.x;
 }
}

// every new instance of b will inherit 'x: 1'
b.prototype = new a();

console.log(b.prototype);

var test=new b();
console.log(test.getX());

查看此链接以获取更多信息 Prototypal inheritance

相关问题