Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/471.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_Ecmascript 5 - Fatal编程技术网

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

JavaScript继承(设置内部原型)失败,javascript,ecmascript-5,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(tes

我试图在构造函数中设置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());

发生的事情是,您正在为b的每个实例创建一个名为“prototype”的公共属性。不是要从中继承的实际原型对象

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());
查看此链接以了解有关的更多信息

好的,我想我已经明白了。因此prototype属性只与构造函数相关,而与实例无关。非常感谢。