Thursday 15 December 2016

Some questions about javascript and objects

Hi, reddit. I'm just begining to developing in node and i have a question about working with objects. So if i has understand well, you can work with objects in node with doing somethink like this:function Point(x, y){ this.x = x; this.y = y; this.getX = function(){ return this.x; }; } var p = new Point(4, 4); console.log(p.getX()); // show 4 But when i begin to learn node, i looking in the source code of express and i see that they doesn't work like this. They work more like this:function Point(x, y){ var obj = {}; obj.x = x; obj.y = y; obj.getX = function(){ return this.x; }; return obj; } var p = Point(4, 4); console.log(p.getX()); // show 4 So my first question is: what is the best between this 2 practice and what is the real difference between this ?Secondly, on the second example, we can do "var p = Point(4, 4);" and the result is the same. What is the real difference between using or not using new? And i find weird to using new work well because in the end, it's not Point object that we get bug it's a object created in Point. Can you explain me this ?PS: i don't know if this subreddit is made for this or if it's authorized to ask questions like this here so if it's not, sorry and ask me to delete this post. PS2: i know that in ECMAScript 6, we will surely stop to work on objects like this and begin to use class keyword, but i want to understand actual working. PS3: Sorry if my English is poor. I try my best.

Submitted December 15, 2016 at 11:05PM by Ulas42

No comments:

Post a Comment