简体   繁体   English

js 对象属性检索在幕后如何工作?

[英]how does js object-property retrieval work behind the scene?

I have an object我有一个对象

var person = {
   firstName: 'David',
   lastName: 'Ferrera',
   age: 30
};

and, I want to access 2 properties:而且,我想访问 2 个属性:

  • person['lastName']
  • person['lastname']

How does this work behind the scene?这在幕后如何运作?

The engine looks at the object itself and checks whether it has the property or not.引擎查看对象本身并检查它是否具有该属性。 If yes, it returns the corresponding value.如果是,则返回相应的值。 If not it gets the object's prototype (which is just and object as well) and repeats the process.如果不是,它获取对象的原型(也就是对象)并重复该过程。 It does that until the property is either found or the currently inspected object doesn't have a prototype.它会这样做,直到找到该属性或当前检查的对象没有原型。 In the last case it returns undefined .在最后一种情况下,它返回undefined

This is all defined in the spec in 9.1.8.1 OrdinaryGet ( O, P, Receiver ) .这都是在9.1.8.1 OrdinaryGet ( O, P, Receiver )的规范中定义的。

Since lastName exists in person , the property is found and Ferrera is returned.由于lastName存在于person ,因此找到了该属性并返回了Ferrera

Since lastname does not exists in person , the engine continues to look at its prototype ( Object.getPrototypeOf(person) ).由于lastname不存在于person ,引擎继续查看其原型( Object.getPrototypeOf(person) )。 Since it doesn't have lastname and it doesn't have a prototype either, undefined is returned.由于它没有lastname ,也没有原型,因此返回undefined

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM