javascript - js 原型链问题
高洛峰
高洛峰 2017-04-10 17:55:56
[JavaScript讨论组]
var proto= {
  age:5
}

var create = function(name){
  var child = Object.create(proto);
  child.name = name;
  return child;
}

var Lee = create('Lee');
console.log(Lee);//{name:"Lee"} ->这里输出的属性为什么没有age?
console.log(Lee.age);//5 ->但是这里却能输出

在《单页Web应用 JavaScript从前端到后台》书中输出的结果和我在浏览器控制台输出的结果完全不一样。

console.log(Lee);//{name:"Lee",age:5} -> 这是书中输出的结果

感觉这本书写得完全不对呀。。。
求解答!!!

高洛峰
高洛峰

拥有18年软件开发和IT教学经验。曾任多家上市公司技术总监、架构师、项目经理、高级软件工程师等职务。 网络人气名人讲师,...

全部回复(5)
PHPz

看这里关于 object.create

The Object.create() method creates a new object with the specified prototype object and properties.

1.console.log(Lee);//{name:"Lee"} ->这里输出的属性为什么没有age?
因为age属性是Lee原型链上层的属性,不是Lee自身属性

2.console.log(Lee.age);//5 ->但是这里却能输出
访问age时,先在Lee里面找,没有,往原型链上找到 ,找到了,就输出原型链上的age

关于原型链,具体看看 javascript高级程序设计 这本书,or 找找其他博客文章~

PHPz

请理解Object.create(),https://developer.mozilla.org...
age的属性是绑定在原型上的

ringa_lee

Object.create ( O [, Properties] )

The create function creates a new object with a specified prototype.
When the create function is called, the following steps are taken:

If Type(O) is not Object or Null throw a TypeError exception.
Let obj be the result of creating a new object as if by the expression new Object() where Object is the standard built-in constructor with that name
Set the [[Prototype]] internal property of obj to O.
If the argument Properties is present and not undefined, add own properties to obj as if by calling the standard built-in function
Object.defineProperties with arguments obj and Properties.
Return obj.

因此console.log(Lee)中,age是在lee.prototype中的。
'-----------------------------------------------------------------------------
楼主新更改的代码中,更改之后都为1的。
console.log(Jessic.age)//输出1
能否贴出你的全部代码还有执行的环境。

ringa_lee
Object.create(prototype, descriptors)

参数
prototype
必需。 要用作原型的对象。 可以为 null。
descriptors
可选。 包含一个或多个属性描述符的 JavaScript 对象。
“数据属性”是可获取且可设置值的属性。 数据属性描述符包含 value 特性,以及 writable、enumerable 和 configurable 特性。 如果未指定最后三个特性,则它们默认为 false。 只要检索或设置该值,“访问器属性”就会调用用户提供的函数。 访问器属性描述符包含 set 特性和/或 get 特性。 有关详细信息,请参阅 Object.defineProperty 函数 (JavaScript)。

天蓬老师

JavaScript中的函数运行在它们被定义的作用域里,而不是它们被执行的作用域里

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

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