Understanding Javascript prototypes coming from Java and C ++ background

My programming background is mostly written in Java, C ++ and C #. I recently got into Javascript and web development, and I have a basic understanding of using Javascript and JQuery to work with elements such as manipulating DOM elements and what I need in the interface.

What I seem to be unable to get around is prototyping in JS. I have read several articles and answers about this, but it still makes no sense to me. I think the best way for me to correctly understand this is with some sort of comparison between JS prototypes and C ++ / Java classes.

So, my last question: Based on the Java / C ++ background, what do I need to know in order to be able to use prototypes effectively in my code?


Side note: questions such as this talk about philosophical differences between the two. I really hope this is an explanation of how to program prototypes aimed at those who already understand how to use classes in C ++.

+4
source share
2 answers

Prototypes and why they are amazing.

Before starting, Mozilla can write this guide better than me: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Introduction_to_Object-Oriented_JavaScript

, . OO. , , ++, , . ++ - , JavaScript .

, JavaScript. ++ , , :

class Rectangle {
    int width, height;
  public:
    void set_values (int,int);
    int area() {return width*height;}
};

++, JavaScript Object

var derek = "Derek Howard";
derek.age = 16;

JavaScript " ", . , Object, , .

, , (, ++). prototype.

"" Javascript?

JavaScript .

Function, . , , ""

(, ) . , Object

function Rectangle(width, height) {
    this.width = width || 1;
    this.height = height || 1;
}

|| , , - .

, "" , .

Rectangle.prototype.area = function () {
    return this.width * this.height;
}

! .

++. new:

var bigRec = new Rectangle(42, 100);

, Rectangle.prototype, :

alert(bigRec.area());

(JSFiddle: http://jsfiddle.net/howderek/H65qs/)

//new class
function Rectangle(width, height) {
    //class properties
    this.width = width || 1;
    this.height = height || 1;
}

//class functions
Rectangle.prototype.area = function () {
    return this.width * this.height;
}

//create a new Rectangle object
var bigRec = new Rectangle(42, 100);
//call functions created from the prototype
alert(bigRec.area());
+3

, , Javascript , , , . " Javascript , ", :

Javascript, CoffeeScript . CoffeeScript OO- , , Java, , Javascript. () Javascript, , .

Coffeescript , , , CoffeeScript Javascript ( , "" ). Javascript , . : ... (-, Java, Javascript).

Coffeescript , , Javascript. "" "" Coffeescript, Javascript. , "".

+1

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


All Articles