[Javascript] Understanding the difference between .prototype and .__proto__ in JavaScript

It can be confusing to understand when and how the .prototype and .proto properties are created and used. They both seem to imply having something to do with prototypal inheritance. This is true but possibly not how you think. We'll review each of these properties' role within prototypal inheritance and how they are used in everyday code.

 

You can create a constructor function in Javascript:

function foo () {}

Once you do it, Javascript will automatcilly create 'prototype' for you:

 

It contians two things by defaults:

  • constructor function which points to foo itself.
  • dunder proto: __proto__, it inherent some methods form Object.

 

Now if we add this code:

foo.prototype.test = "testing"

 

Now let's try to guess what's the output for following code?

console.log(foo.test)

 

..

..

..

 

OK, the Answer is 'undefined'.

 

So, why? we have defined on its prototype, why it is still undefined. It might confuse a lot of people come to Javascript.

Let's use OOP approach to explain what you have done:

class foo {

  public test = 'testing';  

   constructor() {}
}

So, now, if I ask you what's the output of 'foo.test'? You might know the correct answer.

 

If you want to access 'test' prop, you have to do:

const ifoo = new foo()
console.log(ifoo.test) // testing

 

OK, what's happen in Javascript? 

In short, the answer is, when you use 'new' keyword to make a new instance 'ifoo'.

Javascript copy the 'foo.prototyp' which contains {test: 'testing', constructor: foo() {}} to __proto__.

And __proto__ is accessable by instanse which is 'ifoo'.

foo.prototype === ifoo.__proto__
// true

 

Take away: foo.prototype just like define some methods or props inside a Class. The props and methods you have defined cannot be directly access by foo.<prop|method>; To access those, you need to create a new instance, Then the new instance can access it via __proto__

posted @   Zhentiw  阅读(190)  评论(0编辑  收藏  举报
编辑推荐:
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
历史上的今天:
2019-02-21 [React] Safely setState on a Mounted React Component through the useEffect Hook
2018-02-21 [CSS3] All abourt responsive image
2018-02-21 [React] Work with HTML Canvas in React
2017-02-21 [HTML5] Using the tabindex attribute for keyboard accessibility
2016-02-21 [Immutable.js] Differences between the Immutable.js Map() and List()
2016-02-21 [Immutable.js] Using fromJS() to Convert Plain JavaScript Objects into Immutable Data
点击右上角即可分享
微信分享提示