惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
C
CERT Recently Published Vulnerability Notes
C
Cybersecurity and Infrastructure Security Agency CISA
P
Proofpoint News Feed
Security Latest
Security Latest
P
Privacy International News Feed
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
AI
AI
Cisco Talos Blog
Cisco Talos Blog
K
Kaspersky official blog
S
Secure Thoughts
PCI Perspectives
PCI Perspectives
Simon Willison's Weblog
Simon Willison's Weblog
D
DataBreaches.Net
GbyAI
GbyAI
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
大猫的无限游戏
大猫的无限游戏
T
Tailwind CSS Blog
The Cloudflare Blog
阮一峰的网络日志
阮一峰的网络日志
CTFtime.org: upcoming CTF events
CTFtime.org: upcoming CTF events
罗磊的独立博客
V
Visual Studio Blog
aimingoo的专栏
aimingoo的专栏
H
Hackread – Cybersecurity News, Data Breaches, AI and More
IT之家
IT之家
V
V2EX
Last Week in AI
Last Week in AI
有赞技术团队
有赞技术团队
月光博客
月光博客
酷 壳 – CoolShell
酷 壳 – CoolShell
T
Tenable Blog
T
Threat Research - Cisco Blogs
T
Troy Hunt's Blog
V2EX - 技术
V2EX - 技术
S
Security @ Cisco Blogs
Security Archives - TechRepublic
Security Archives - TechRepublic
Project Zero
Project Zero
The GitHub Blog
The GitHub Blog
Recent Commits to openclaw:main
Recent Commits to openclaw:main
L
Lohrmann on Cybersecurity
F
Full Disclosure
H
Help Net Security
博客园 - Franky
Stack Overflow Blog
Stack Overflow Blog
N
Netflix TechBlog - Medium
Engineering at Meta
Engineering at Meta
A
Arctic Wolf
O
OpenAI News
S
Securelist

JavaScript iDiallo.com

How to tell an element is in view using JavaScript. Complex function call delays without nesting in JavaScript How to use pushState without breaking the back button How to create DOM elements efficiently with JavaScript Uncaught TypeError: Cannot read property of null Optimization: Minimize look-ups in for loops. Uncaught SyntaxError: Unexpected token < Magical JavaScript Live Collection Creating a class in JavaScript
Why Use Prototype in JavaScript
Ibrahim Dial · 2017-11-14 · via JavaScript iDiallo.com

Why Use Prototype in JavaScript

JavaScript Notes

Practical tips and subtle gotchas from real production experience.

There is a clear reason why you should use prototypes when creating classes in JavaScript.

They use less memory.

When a method is defined using this.methodName a new copy is created every time a new object is instantiated. Let's look at an example.

In most Object Oriented programming languages a class has a constructor. A constructor is a sort of initializing function that is called every time a new instance of the class is created. Usually the Constructor function name is defined using the actual class name or the keyword constructor:

// In Java
public class Animal {

    private String _name;
    // constructor function
    public Animal(name){
        // this content will be executed when an instance is created:
        // Ex: Animal cat = new Animal('cat');

        _name = name;
    }

}

// In PHP
class Animal {

    private $name;
    public function __constructor($name){
        // this content will be executed when an instance is created:
        // Ex: $dog = new Animal('dog');

        $this->name = $name;
    }

}

But how about in JavaScript? Do we have a constructor? Yes we do, only everything in JavaScript is a weird, so the constructor is the class/function/constructor itself.

// In JavaScript
function Animal(name){
    // this is the class and the constructor at the same time.
    // Ex: var cat = new Animal('cat') 
    this.name = name;
}

So when we call new Animal() the constructor is called immediately. This is where the problem of performance occurs. Imagine I define three functions inside the constructor, this means every single time, those functions are defined anew.

function Animal(){
    this.walk = function(){};
    this.talk = function(){};
    this.jump = function(){};
}

We are creating duplicate functions every single time. If I create two or three objects, then the problem is negligible. But if we create a herd of animals, we start seeing our memory growing because for each animal we are creating a whole new method at run time/instance time.

var cat = new Animal();
var dog = new Animal();
(cat.walk === dog.walk) // false 

The walk of the first object is different then the walk of the second object because each was created during instantiation. In other words, Animal does not know that the method walk() exists before being instantiated.

The solution to the problem is to use Prototypes. What it does is allow us to define the methods once, as a blue print, and have each instance build from it.

function Animal(){};
Animal.prototype.walk = function(){};
Animal.prototype.talk = function(){};
Animal.prototype.jump = function(){};

Now any new instance has a blue print of the class before being created. So every walk is a walk, and every jump is a jump:

var cat = new Animal();
var dog = new Animal();
(cat.walk === dog.walk) // true

Imagine creating a virtual DOM where each DOM element has a few methods. If you use the non-prototypical way with this you will be recreating each method for each virtual DOM element. Shortly after you will notice your application slowing down. But use prototypes and the methods are defined only once thus take much less memory. This is similar to how jQuery defines methods for DOM elements. They don't create a new .css for each element for example, they define it once using a prototype.

The only inconvenience of using prototypes is that there is no easy way to create private methods or variables.

function Animal(){
    // this varialbe is private
    var private_var = 10;

    // this function is public
    this.walk = function(){};

    // this function is private
    function dance(){}
}

How you plan to use a class should be the deciding factor for using prototype or non-prototype methods. If you are going to create a lot of instances, use prototypes.


Did you like this article? Subscribe for more and follow updates via RSS.

Back to JavaScript articles