Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.javascript > #23053

Re: Cons in the following object implementation

Message-ID <1476035.p2tWUPlOUs@PointedEars.de> (permalink)
From Thomas 'PointedEars' Lahn <PointedEars@web.de>
Organization PointedEars Software (PES)
Date 2014-02-10 14:53 +0100
Subject Re: Cons in the following object implementation
Newsgroups comp.lang.javascript
References <76619944-f726-4102-a16c-0eceddb251a0@googlegroups.com>

Show all headers | View raw


Alon Melanker wrote:

> On a job interview, I've been asked to defined an object with a private
> variable and getter/setter for this private variable.
> 
> I chose the following:
> 
> var obj = function() {
>    var private;
>    
>    this.setPrivate(val) {
>       private = val;
>    }
>    
>    this.getPrivate() {
>       return private;
>    }
> };
> 
> 
> When I've finished to implement the object the interviewer told me there
> are some problems\cons with this object and those "problems" are not the
> setter/getter functions.
> 
> I've been asked to point out those flaws, but I couldn't.
> 
> Does anyone can point out the flaws in the object?

This program is syntactically in error, which you would have known if you 
had tried to run it before you asked.

If one mentally corrected the syntax errors, it would still be 
*semantically* in error, which you had known if you knew the first thing 
about these languages: “obj” would refer to a *Function* instance that, when 
called in non-strict mode, returned “undefined”; a function that, when 
called in strict mode, would throw a ReferenceError exception because “this” 
would be “undefined”.

The correct code – also called the Module Pattern – is

  var obj = (function () {
    /* The underscore for privates is a matter of preference only */
    var _private;
   
    return {
      setPrivate: function (val) {
        _private = val;
      },
   
      getPrivate: function () {
        return _private;
      }
    };
  }());

You should not consider applying for another job of this kind before you 
have understood and can explain in correct terminology why this is the 
correct code.  This is _not_ “JavaScript 101”.  Do your own homework.

<http://PointedEars.de/faq#posting>

-- 
PointedEars

Twitter: @PointedEars2
Please do not Cc: me. / Bitte keine Kopien per E-Mail.

Back to comp.lang.javascript | Previous | Next — Previous in thread | Find similar | Unroll thread


Thread

Cons in the following object implementation Alon Melanker <melankeril@gmail.com> - 2014-02-10 04:21 -0800
  Re: Cons in the following object implementation "Evertjan." <exxjxw.hannivoort@inter.nl.net> - 2014-02-10 13:33 +0100
    Re: Cons in the following object implementation Alon Melanker <melankeril@gmail.com> - 2014-02-10 05:22 -0800
  Re: Cons in the following object implementation Thomas 'PointedEars' Lahn <PointedEars@web.de> - 2014-02-10 14:53 +0100

csiph-web