javascript - 面试遇到的一个问题,小白求教关于原型链的
ringa_lee
ringa_lee 2017-04-10 17:27:00
[JavaScript讨论组]
function C1(name){
    if(name) this.name=name;
}
function C2(name){
    this.name=name;
}
function C3(name){
    this.name=name||'john';
}
//
C1.prototype.name="Tom";
C2.prototype.name="Tom";
C3.prototype.name="Tom";
alert((new C1().name)+(new C2().name)+(new C3().name));
//我理解的本地name都没声明,访问的都是prototype的name属性
//所以有个疑问就是没有声明的属性也可以去原型里找吗
//不是应该声明没赋值才有用么
ringa_lee
ringa_lee

ringa_lee

全部回复(4)
伊谢尔伦

你的问题在于在构造实例时没有声明name,因为根本没有为构造函数传参数,那么真是如此吗?

function test(t) {
    console.log(t);//undefined
    console.log(a);//报错
}
test();

可以看到,即使没有给一个带参的函数传参,也能访问到这个参数,这个参数的值是undefined
这其实涉及到arguments,js函数定义时的参数其实是不必要的,因为函数内部其实访问的是一个类数组对象arguments,传进来的参数依次放到这个对象中。

function test(t) {
    console.log(arguments[0]);//undefined
    console.log(arguments[1]);//undefined
}
test();

所以第一个构造函数没有声明和初始化name,实例去原型中找name属性。但剩下的两个构造函数为name赋值undefined
所以这道题的答案是:Tomundefinedjohn

天蓬老师


来自JavaScript高级程序设计(第三版)
MDN上的例子

// Let's assume we have object o, with its own properties a and b:
// {a: 1, b: 2}
// o.[[Prototype]] has properties b and c:
// {b: 3, c: 4}
// Finally, o.[[Prototype]].[[Prototype]] is null.
// This is the end of the prototype chain as null,
// by definition, null has no [[Prototype]].
// Thus, the full prototype chain looks like:
// {a:1, b:2} ---> {b:3, c:4} ---> null

console.log(o.a); // 1
// Is there an 'a' own property on o? Yes, and its value is 1.

console.log(o.b); // 2
// Is there a 'b' own property on o? Yes, and its value is 2.
// The prototype also has a 'b' property, but it's not visited. 
// This is called "property shadowing"

console.log(o.c); // 4
// Is there a 'c' own property on o? No, check its prototype.
// Is there a 'c' own property on o.[[Prototype]]? Yes, its value is 4.

console.log(o.d); // undefined
// Is there a 'd' own property on o? No, check its prototype.
// Is there a 'd' own property on o.[[Prototype]]? No, check its prototype.
// o.[[Prototype]].[[Prototype]] is null, stop searching,
// no property found, return undefined
黄舟

C1,if不成立,new C1()中没有name属性,就访问到了原型上的name,输出tom
C2,既然没有参数,也就是执行new C2(undefined),所以name为undefined
C3,new C3()的name值为john,所输出john

迷茫

proto

热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习
PHP中文网抖音号
发现有趣的

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号