作用域链(继承体现)
?
- ?????
- function?MyOne(?number?)?{??
- ?????this.number?=?number;??
- }??
- function?MyTwo(?name?)?{??
- ?????this.name?=?name;??
- }??
- ??
- MyTwo.prototype?=?new?MyOne(?8?);??
- var?test?=?new?MyTwo(?"HuJin"?);??
- ??
- alert(?test.__proto__.hasOwnProperty(?"constructor"?)?);?//?false??
- alert(?var?val?=?test.name?);?//?"HuJin"??
- alert(?var?val?=?test.number?);?//?8??
??
自己的思考
alert( test.name )的查找顺序为:
1. if(?test.hasOwnProperty(?"name" ) ) // Yes
2. var val = test.name // val = "HuJin"
3. alert(val);
?
输出结果:
?
alert( test.number )的查找顺序为:
1. if( test.hasOwnProperty( "number" ) ) // No
2. then 查找 test的原型 new MyOne( 8 ),因为test的构造函数 new MyTwo()的原型对象是一个MyOne的实例
?? 代码相当于:
?? else if( test.__proto__.hasOwnProperty( "number" ) ) // Yes
3. var val = test.__proto__.number // val = 8;如果仍然找不到number属性,则继续向原型链上方走
4. else if( test.__proto__.hasOwnProperty( "number" ) ) // No
5. then if( test.__proto__.__proto__.hasOwnProperty(?"number" )) // Yes
? ? then val = test.__proto__.__proto__.number // 这时test.__proto__.__proto__应该指向MyOne.prototype
?? 验证一下 : alert(test.__proto__.__proto__ === MyOne.prototype) // 神奇般的对了,参照上面的图
?
输出结果:
6. 如果还是找不到
? ? if( test.__proto__.__proto__.hasOwnProperty(?"number" ))?// No 那么继续向上走,也就是从MyOne.prototype向上走,也就到了Object对象了。
?
Extra:
我们在Object.prototype上增加一个奇怪的"monk"属性,然后调用 alert( test.monk?)测试一下,看看是否会继续往上找...
?
输出结果:?
?
该告一段落了。如果在Object.prototype中还是查找不到,那么undefined就弹出来了。也就是说访问不存在的属性,会一直遍历整个原型链。