Javascript Prototype And Prototype Chain

Concept

Each object in javascript has a private property called Prototype, which is like a pointer referring to another object in every instances. Prototype is shared by all instances, so two different objects could access common properties and methods on the prototype if they have the same prototype, and modifying property on the prototype will affect the following access. Each object has its own prototype, which may also has its prototype until the Object finally, which forms the prototype chain. Therefore, Object is at the root of the prototype chain, the ancestor of all object instances. All objects “inherit” from Object. Object itself also has prototype, which is null, while null doesn’t has any prototype. Generally, an object i.e an array, has the prototype of Array, which has the prototype of Object. In the examples, the variable, prototype Array and prototype Object form the prototype chain. Any objects in javascript has such prototype chain, longer or shorter.

Usage

Prototype is fundamentally used for property(or method) lookup. For instance, we create an variable that is an Array, i.e, var array = []. Then the variable array’s prototype is Array, and its prototype is Object, which make up of the prototype chain. When accessing the method toString(), the process of the lookup will be: search array’s own properties to see whether toString() method exist. If so, return that function and the lookup is finished. Otherwise, search the prototype of array, Array, to see whether it has the method. If so, return the method and the lookup is finished. Otherwise, search the prototype of Array, Object, for toString() method. If so, return the method and the lookup is finished. Otherwise, return undefined because it reach the root of the prototype chain. Of course, Object has toString() method.
As property and method lookup process will enumerate all enumerable properties and methods in the object, the time for lookup will be critically longer for those instances with a long prototype chain. This may lead to performance problems if neglecting your object prototypes

Object.getPropertyOf() and Object.setPrototypeOf()

getPrototypeOf() and setPrototypeOf() methods provide interfaces to access and modify an object’s prototype. We should always use these methods to access the prototype instead of __proto__ implemented by Chrome or some other browser vendors. Also, Object.create() method could pass in an object as the prototype of the object to be created.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值