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

查看:126
本文介绍了javascript - 求高手回答原型继承的问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问 题

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环境就可以?

解决方案

题主:代码可以再捋一捋

Child.prototype=Parent.prototype    // Parent.prototype指向的是Object
Child.prototype=Parent    //该是这样吧

第一个问题:this不能获得构造函数Parent的原型

function Child() 定义一个函数,使用var c = new Child() this的指向为对象c,就没指向 Parent,不过你使用c.showName(),还是能获取到的,因为原型继承.

第二个问题:写在Child函数里不行,为什么拿出来写在window环境就可以?

写在函数里面也行的, this.prototype=Parent;
一个new做了以下几件事情:

  1. 创建一个新的对象

  2. 查找Childprototype上的所有方法、属性,复制一份给创建的对象

  3. 将构造函数Child内部的this指向创建的对象

  4. 创建的对象的__proto__指向Childprototype

  5. 执行构造函数

  6. 返回新创建的对象给变量c

写在内部就是在第五部写入,写在外部是在第四部写入,故与内外无关。

这篇关于javascript - 求高手回答原型继承的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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