SitePoint Sponsor

User Tag List

Results 1 to 5 of 5

Thread: Lacking scope

  1. #1
    SitePoint Member
    Join Date
    Feb 2008
    Posts
    4
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Lacking scope

    Hi all,

    I can't figure out why the alertDraggable function does have access to the this variable (refering to the object instance), and the onClick function (invoked from within the VE API) doesn't. I appreciate your advise.

    Code:
    ULAB.GeoCMS.Core.Shape = Class.extend({
        initialize: function(type, points) {
            this.veShape = new VEShape(type, points);
            this.locked = true;
            this.previousLocation = null;
            this.draggable = true;
            this.core = ULAB.GeoCMS.Core.Register.getEntry('core');
            this.map = core.getMap();
            this.map.AttachEvent("onclick", this.onClick);
        },
        alertDraggable: function() {
             alert(this.draggable); //true
        },
        onClick: function() {
             alert(this.draggable); //undefined
        });
    Note: the code uses the inheritance model as described at: http://twologic.com/projects/inheritance/

    Thanks in advance!
    Last edited by ulab; Feb 25, 2008 at 06:15.

  2. #2
    SitePoint Wizard
    Join Date
    Dec 2003
    Location
    USA
    Posts
    2,582
    Mentioned
    29 Post(s)
    Tagged
    0 Thread(s)
    This may have nothing to do with it, but the only difference I noticed was that the alert in alertDraggable had a semi-colon at the end whereas onClick's didn't. Try adding one and seeing if that changes anything. Other then that, I don't really see anything that should be different.

    You could always have onClick call the alertDraggable function if they are meant to do the same thing.

  3. #3
    SitePoint Member
    Join Date
    Feb 2008
    Posts
    4
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Thanks for your reply. Sorry my fault typo, the semi-colon has indeed nothing to do with it.

    Other suggestions?

  4. #4
    SitePoint Wizard silver trophy kyberfabrikken's Avatar
    Join Date
    Jun 2004
    Location
    Copenhagen, Denmark
    Posts
    6,157
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Because this is a reference to the calling context -- Not to the owning object. This is different in Javascript, than in class based languages. Use a closure to remedy:
    Code:
    var self = this;
    this.map.AttachEvent("onclick", function() {
      self.onClick();
    });

  5. #5
    SitePoint Member
    Join Date
    Feb 2008
    Posts
    4
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Thanks! By the way, in the mean time I found an excellent article about this subject at http://www.digital-web.com/articles/...in_javascript/.


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •