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

推荐订阅源

博客园 - Franky
WordPress大学
WordPress大学
Hugging Face - Blog
Hugging Face - Blog
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
小众软件
小众软件
人人都是产品经理
人人都是产品经理
罗磊的独立博客
博客园 - 聂微东
雷峰网
雷峰网
量子位
美团技术团队
V
V2EX
The GitHub Blog
The GitHub Blog
大猫的无限游戏
大猫的无限游戏
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
IT之家
IT之家
The Cloudflare Blog
爱范儿
爱范儿
T
Tailwind CSS Blog
博客园 - 三生石上(FineUI控件)
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
宝玉的分享
宝玉的分享
Last Week in AI
Last Week in AI
Jina AI
Jina AI

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