Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Day98:写出下面代码的执行结果,并解释原因 #910

Open
Genzhen opened this issue Jul 16, 2020 · 3 comments
Open

Day98:写出下面代码的执行结果,并解释原因 #910

Genzhen opened this issue Jul 16, 2020 · 3 comments
Labels
JavaScript teach_tag

Comments

@Genzhen
Copy link
Collaborator

Genzhen commented Jul 16, 2020

Object.prototype.yideng = "京程一灯";
var a = 123;
a.b = 456;
console.log(a.yideng);
console.log(a.b)

// 写出执行结果,并解释原因

@Genzhen Genzhen added the JavaScript teach_tag label Jul 16, 2020
@Genzhen
Copy link
Collaborator Author

Genzhen commented Jul 16, 2020

每日一题会在下午四点在交流群集中讨论,五点 Github、交流群同步更新答案

扫描下方二维码,收藏关注,及时获取答案以及详细解析,同时可解锁800+道前端面试题。

@tunshiyu
Copy link

console.log(a.yideng); // 京程一灯
console.log(a.b) ; //undefined

解释

var a  // 声明提升
Object.prototype.yideng = "京程一灯";  // 向对象添加属性,此时a对象身上有此属性
a = 123; //赋值,a为数字类型
a.b = 456;  // 数字类型无法这样赋值,所以打印undefined

@mufengchun
Copy link

mufengchun commented Jul 22, 2020

结果:
console.log(a.yideng); // 京程一灯
console.log(a.b) ; //undefined

解析:
var 定义赋值 a 的时候, a 的变量提升成为了 Number类型;Number本身就是一个对象,可以继承 Object 的属性,因此 a.proto 是存在 yideng 这个键的;a 本身作为 Number 类型的值,是不可以设置 键的,所以 a.b 是不存在的

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
JavaScript teach_tag
Projects
None yet
Development

No branches or pull requests

3 participants