Path: csiph.com!aioe.org!.POSTED!not-for-mail From: Joao Rodrigues Newsgroups: comp.lang.javascript Subject: Re: Newbie trying to understand object oriented programming Date: Sat, 6 Feb 2016 11:56:22 -0200 Organization: Aioe.org NNTP Server Lines: 99 Message-ID: References: <664696a0-3ce3-484c-aeaf-2fdf45781bb4@googlegroups.com> NNTP-Posting-Host: 5oq0M7qGeWhU/PcHEWLGrQ.user.gioia.aioe.org Mime-Version: 1.0 Content-Type: text/plain; charset=windows-1252; format=flowed Content-Transfer-Encoding: 7bit X-Complaints-To: abuse@aioe.org User-Agent: Mozilla/5.0 (X11; Linux x86_64; rv:38.0) Gecko/20100101 Thunderbird/38.5.1 X-Notice: Filtered by postfilter v. 0.8.2 Xref: csiph.com comp.lang.javascript:29561 bit-naughty@hotmail.com wrote: > Hi, OK, I've read about and tried to understand OOP for a long time > now, but I don't think I really get it. In this case, I'd suggest reading this article in MDN: > This question just popped > into my head while mulling the whole thing over: > > "this" means *that one*, right? Like, it's a cookie cutter.....? > > Then what about this?: > > if I have: > > function vegetables() { this.colour="brown"; } There is a convention about constructor functions that their names should start with an upper case letter. Then you should write: function Vegetables() { this.colour = "brown"; } > > and I do both a var potatoes = new vegetables() ; > > AND a var tomatoes = new vegetables(); > > > Then BOTH potatoes.colour will be "brown" *AND* tomatoes.colour will > be "brown", right.....??!!! Yes, because all instances of Vegetables will have the property 'colour' with the same value ('brown'). You should have declared Vegetables() as: function Vegetables(colour) { this.colour = colour; } var tomato = new Vegetables('red'); console.log(tomato.colour); // red var potato = new Vegetables('brown'); console.log(potato.colour); // brown Douglas Crockford once wrote: "JavaScript is a prototypal language, but it has a *new* operator that tries to make it look sort of like a classical language. That tends to confuse programmers, leading to some problematic programming patterns." It would be simpler if you used: var vegetables = { tomatoes: { colour: 'red' }, potatoes: { colour: 'brown' } }; It is even simpler if you need to add properties to vegetables: vegetables.bananas = {colour: 'yellow'}; var tomato = vegetables.tomatoes; console.log(tomato.colour); // red var potato = vegetables.potatoes; console.log(potato.colour); // brown var banana = vegetables.bananas; console.log(banana.colour); //yellow ECMAScript 2015 (aka ES6) introduced "class", which is a syntactical sugar over JavaScript's existing prototype-based inheritance. See: class Vegetables { constructor(colour) { this.colour = colour; } } var potatoes = new Vegetables('brown'); console.log(potatoes.colour); // brown -- Joao Rodrigues