求高手回答原型继承的问题

function Parent(firstName,color){

    this.firstName = firstName;

    this.color = color;

    this.showName = function (){

        console.log("我家姓氏:"+this.firstName);

    }

}

Parent.prototype.showAll=function(){

    console.log("姓:"+this.firstName+"\n"+"喜爱的颜色:"+this.color);

}

function Child(myName,age,firstName,color){

    this.myName = myName;

    this.age = age; 

    Child.prototype=Parent.prototype;

    Parent.call(this,firstName,color);

}

/*Child.prototype=Parent.prototype;*/


var c = new Child("帅",23,"孙","粉色");

var d=new Parent("孙","粉色");

d.showAll();//姓:孙

            //喜爱的颜色:粉色

c.showAll();//error c.showAll is not a function


call对象冒充为什么this不能获得构造函数Parent的原型?还有Child.prototype=Parent.prototype;写在Child函数里不行,为什么拿出来写在window环境就可以?


眼眸繁星
浏览 456回答 1
1回答

尚方宝剑之说

题主:代码可以再捋一捋Child.prototype=Parent.prototype    // Parent.prototype指向的是ObjectChild.prototype=Parent    //该是这样吧第一个问题:this不能获得构造函数Parent的原型function Child() 定义一个函数,使用var c = new Child() this的指向为对象c,就没指向 Parent,不过你使用c.showName(),还是能获取到的,因为原型继承.第二个问题:写在Child函数里不行,为什么拿出来写在window环境就可以?写在函数里面也行的, this.prototype=Parent;一个new做了以下几件事情:创建一个新的对象查找Child的prototype上的所有方法、属性,复制一份给创建的对象将构造函数Child内部的this指向创建的对象创建的对象的__proto__指向Child的prototype执行构造函数返回新创建的对象给变量c写在内部就是在第五部写入,写在外部是在第四部写入,故与内外无关。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript