locked
winjs class question

    Question

  • Hi, all

    If I have a class likes this.

    WinJS.Class.define( function () {
    // here is the constructor.
    
    }, {
    // public member
       f1: function () {
          this.var_a;  // ok
          this._f1(); // fail! :(
       }
    }, {
    // static member
       
       var_a: null,
       _f1: function () {
         // do something.
       }
    });

    why can't I use _f1 function in my public member but access var_a is OK?

    thanks in advance...


    • Edited by gogoqaz Friday, February 7, 2014 8:47 AM
    Friday, February 7, 2014 8:45 AM

Answers

  • A public or instance member like f1 must always be called on an instance of the object. That is, if you do var obj = new <yourClass>, then you can call obj.f1.

    Static members must be referenced through the fully qualified name of the class. In your case <yourClass>._f1 or <yourClass>.var_a. So in your f1 implementation, you's need to do <yourClass>._f1 explicitly, rather than this._f1 which is trying to find an instance member that doesn't exist.

    The reason this.var_a works is because JavaScript isn't always picky about undeclared variables. this.var_a is NOT the same as <yourClass>.var_a because one is an instance member and the other is a static member. If you want to talk to the static member you have to use <yourClass>.var_a instead.

    I would recommend you include "use strict"; at the top of your JS file, by the way, as this will cause the engine to flag any undeclared variables. I would expect that this will raise an exception on this.var_a.

    Kraig

    Author, Programming Windows Store Apps with HTML, CSS, and JavaScript, Second Edition, a free ebook from Microsoft Press. First edition (for Windows 8) also available.


    Friday, February 7, 2014 5:30 PM