Win a copy of Head First Android this week in the Android forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Tim Cooke
  • Campbell Ritchie
  • Paul Clapham
  • Ron McLeod
  • Liutauras Vilda
Sheriffs:
  • Jeanne Boyarsky
  • Rob Spoor
  • Bear Bibeault
Saloon Keepers:
  • Jesse Silverman
  • Tim Moores
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
Bartenders:
  • Piet Souris
  • Al Hobbs
  • salvin francis

Strange Behavior of Instance field scope in Object Oriented Javascript

 
Ranch Hand
Posts: 205
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I have recently started following Javascript and that too Object Oriented JS and also i am impressed with Object Oriented JS except for its poor support for collections. Anyways getting back to the main topic..As an exercise i tried to create a Validation library for my application but it seems the instance values scopes are either not understood by me or else this is strange behavior. In order to illustrate this behavior i have sliced down the library to basic minimum in order to present here.

  • The below given sample validates if the email format is correct or not.
  • The problem is visible when you enter the correct format like
    johndoe@gmail.com and click submit.
  • It will trigger the registered event which modifies the IS_ERROR
    instance field to false and displayed by alert 1.
  • Then if you click the submit button the update function is triggered by onclick event of the submit button that tries to display the
    IS_ERROR value again as per the alert 2.


  • surprizingly these two values are different. How is that possible?
    What am i missing?

    test.html


    validations.js

     
    Bartender
    Posts: 2968
    6
    • Likes 1
    • Mark post as helpful
    • send pies
      Number of slices to send:
      Optional 'thank-you' note:
    • Quote
    • Report post to moderator

    shukla raghav wrote:surprizingly these two values are different. How is that possible?
    What am i missing?



    You don't understand what "this" is in JavaScript. You are treating it as the object that the function is attached to. But in fact it is the object that the function is invoked on - a subtle but important difference; in JavaScript this is called the function context. In JavaScript one function from one object can be borrowed to operate on another object - example:

    The standard arguments object is "Array-like" but it doesn't have a slice method. The above code shows how to "borrow" the slice method from the prototype found on the Array constructor function to use slice on an arguments object.
    Your code registers an event handler. window invokes all event handlers, so in the event handler "this" is window not window.registry as you are expecting.

    In ES5 Function.prototype.bind() was introduced to get around the problem.

    However it has always been simpler to capture the desired "this" value in a variable in the function closure and use that instead of "this":

     
    Sheriff
    Posts: 67595
    173
    Mac Mac OS X IntelliJ IDE jQuery TypeScript Java iOS
    • Mark post as helpful
    • send pies
      Number of slices to send:
      Optional 'thank-you' note:
    • Quote
    • Report post to moderator

    Peer Reynders wrote:You don't understand what "this" is in JavaScript. You are treating it as the object that the function is attached to. But in fact it is the object that the function is invoked on - a subtle but important difference; in JavaScript this is called the function context.


    Indeed. Functions in JavaScript are very different from the methods that you may used to in Java. Chapters 3 through 5 in my Secrets of the JavaScript Ninja book go into great detail on JavaScript functions.

    Also, be aware that the prototype-based object-oriented approach in JavaScript is far different from classical OO. Sometimes I think that knowing Java is more of an impediment to learning JavaScript than a help. Be sure not to try and take OO in JavaScript beyond what is natural to the language. Be sure to embrace the functional nature of JavaScript and not rely over-heavily on the OO aspect.
     
    shukla raghav
    Ranch Hand
    Posts: 205
    • Mark post as helpful
    • send pies
      Number of slices to send:
      Optional 'thank-you' note:
    • Quote
    • Report post to moderator

    Sometimes I think that knowing Java is more of an impediment to learning JavaScript than a help. Be sure not to try and take OO in JavaScript beyond what is natural to the language. Be sure to embrace the functional nature of JavaScript and not rely over-heavily on the OO aspect.



    Yes Mr. Bibeault, exactly that was my feeling while i started exploring object oriented javascript. There are certain features in OO based JS that at once seem like a great feature but you exactly don't know how are these utilized in a practical application. At one point i thought why not to go ahead with purely functional way of JS but then being a java developer the ease and manageability aspect of OO paradigm pushes you to go for the Object Oriented version of a technology.

    Since Mr Raynders has well elucidated the strange capabilities of javascript, i have used the later approach he has suggested and works well for me. Thank you Mr Raynders.
     
    Peer Reynders
    Bartender
    Posts: 2968
    6
    • Mark post as helpful
    • send pies
      Number of slices to send:
      Optional 'thank-you' note:
    • Quote
    • Report post to moderator
    Glad to be of help.

    Secrets of the JavaScript Ninja (2013): 3.1 What’s with the functional difference? wrote:Because JavaScript, as the old joke ... goes, is to Java as hamburger is to ham; both are delicious, but they don’t have much in common except a name.



    shukla raghav wrote:being a java developer the ease and manageability aspect of OO paradigm pushes you to go for the Object Oriented version of a technology.


    The primary concepts of object orientation are encapsulation, inheritance, and polymorphism - JavaScript supports all those quite well. The big difference is that Java "practices" class-based OO; JavaScript on the other hand went the prototypal OO route. Implementation inheritance tends to be the most overused and abused feature in OO implementations and the GangOfFour advise us to "Favor 'object composition' over 'class inheritance'". When practicing OO, inheritance should take a back seat to polymorphism - which JavaScript accomplishes with duck typing (notice how the JavaScript version is much more succinct than the Java version). The "JavaScript Way" can feel strangely liberating once you manage wrap your mind around it.

    In dynamic languages testing is incredibly important, so you may want to have a look at Jasmine (I personally prefer the mocha/chai/sinon combo as they can be easily used in both client and server-side JavaScript) and Karma as a browser based test runner.

    If you miss static typing take a look at TypeScript - and before you go stomping off because I just mentioned a Microsoft developed technology, consider that it is being used by Google for Angular 2. At the very least the TypeScript type definitions over at DefinitelyTyped are incredibly useful in editors like IntelliJ WebStorm for coding assistance.
    reply
      Bookmark Topic Watch Topic
    • New Topic