Why do I need to use Javascript Object Prototype

I've been working with JavaScript for quite some time now, and I use objects a lot, but I'm always curious when I need to use prototypes! if I need a new method for an object, I just go on to edit this object and add this method, and in most cases I know what properties and methods I need when creating the object.

what I sowed in prototypes that I can make an object inherited from another:

    var Person = function(firstname,lastname) {
        this.first_name = firstname;
        this.last_name = lastname;
    };

    var employee = function(name) {
    this.name = name;
    };

   employee.prototype = new Person();

when do i really need to use prototypes or what is the best way to use prototypes?

Hello,

+4
source share
2 answers

Just two common use cases:

1) Quick instance creation

- , :

var Person = function(firstname,lastname) {
     this.first_name = firstname;
     this.last_name = lastname;
     this.sayName = function () {
         alert("Hi, my name is " + this.first_name + " " + this.last_name);
     };
};

, , , , . , :

var Person = function(firstname,lastname) {
     this.first_name = firstname;
     this.last_name = lastname;
};

Person.prototype.sayName = function () {
    alert("Hi, my name is " + this.first_name + " " + this.last_name);
};

2)

prototype ( ) . :

Array.prototype.forEach = function (callback) {
    for (var i = 0; i < this.length; i++) {
        callback(this[i], i);
    }
};

var arr = [1,2,3,4];
arr.forEach(function(item, index) {
    console.log(item);
});

, , .

+3

, , , , .

, . A B , C A, B .

, , . , .

+2

Source: https://habr.com/ru/post/1523524/


All Articles