麻烦老师解答,标识的地方代码的含义,还有属性的继承
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 | function People(name, age, sex) { this .name = name; this .age = age; this .sex = sex; this .arr = [1, 2, 3]; } People.prototype.sayHello = function () { console.log( "你好,我是" + this .name); }; function Student(name, age, sex, school, stuNum) { People.call( this , name, age, sex); this .school = school; this .stuNum = stuNum; } function Bread(color, name) { this .color = color; this .name = name; } //原型链继承,继承于同一个people var xh = new Student( "小明" , 20, "女" , "清华大学" , 1002); xh.__proto__ = new People(); //-->这里 console.log(xh.color, xh.name); xh.sayHello(); xh.__proto__ = new Bread( "红色" , "面包" ); //-->这里 console.log(xh.color); console.log(xh.name); |
13
收起
正在回答 回答被采纳积分+1
1回答
好帮手慕星星
2022-12-10 16:14:48
同学你好,解答如下:
1、可以先看构造继承的结果
实例对象xh的原型指向Student构造函数,也就是xh.__proto__的结果是Student构造函数
2、接下来改变实例原型指向为People实例
可以看到xh对象原型不再是Student构造函数,为People实例
现在xh对象中没有color属性,输出值为undefined。name会先找实例上的,结果为‘小明’。
3、接下来改变实例原型指向为Bread实例
原型指向会被覆盖为Bread实例,没有People实例了
输出color值为‘红色’,输出name值实例上的值“小明”(如果实例上没有name属性才会输出原型上的值‘面包’)。
祝学习愉快!
恭喜解决一个难题,获得1积分~
来为老师/同学的回答评分吧