简体   繁体   中英

When should I use “prototype” in JavaScript

I have done a fair amount of programming in JavaScript/JQuery.

But I never used "prototype". In fact, I have no clue what it means.

Do you have a practical example when it is useful?

Simplest example:

function Foo() {
    this.bar = function() {
        return 42;
    }
}

Now you can create as many instances of Foo as you want and call bar() :

var a = new Foo();
var b = new Foo();

Even though both object have bar() method which is exactly the same in both cases, these are distinct methods. In fact, each new Foo object will have a new copy of this method.

On the other hand:

function Foo() {}
Foo.prototype.bar = function() {
    return 42;
}    

has the same end result but the function is stored only once in object prototype rather than in an object itself. This may be a deal breaker if you create tons of Foo instances and want to save some memory.

Assuming you are asking about Object.prototype,

All objects in JavaScript are descended from Object; all objects inherit methods and properties from Object.prototype, although they may be overridden. For example, other constructors' prototypes override the constructor property and provide their own toString methods. Changes to the Object prototype object are propagated to all objects unless the properties and methods subject to those changes are overridden further along the prototype chain.

Read this and then probably this

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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