• We’re currently investigating an issue related to the forum theme and styling that is impacting page layout and visual formatting. The problem has been identified, and we are actively working on a resolution. There is no impact to user data or functionality, this is strictly a front-end display issue. We’ll post an update once the fix has been deployed. Thanks for your patience while we get this sorted.

Javascript confusion...

Code:
var serverAPI = {
    port:8080,
    frontController:"FrontController",
    mainURL:function(){return "localhost:"+this.port+"/"+this.frontController+"/";}
};

//this prints "localhost:8080/FrontController/" to console
console.log(serverAPI["mainURL"]());

//this prints "localhost:undefined/undefined/" to console
var aFunction = serverAPI["mainURL"];
console.log(aFunction());

I was going to ask why this happens... they should print out the same thing to console. I just came up with a theory though.

Is it because when I fetch the function and store it as "aFunction" then the "this" keyword no longer has the same scope it did before? So it cant access port or frontController. Is that whats happening here?
 
When you execute aFunction() in your last line of code the 'this' that is being referenced in the method body is not your instance of serverAPI, but whatever 'this' is assigned to in your global namespace, usually something like the document or window object in a browser JS context or a global object in a serverside JS context.


If you did the following you would get the results you are expecting.
Code:
console.log(aFunction.call(serverAPI));
 
You might find something like this interesting

Code:
var ServerAPI = function(port, frontController){
    Object.defineProperties(this, {
        "port": { get: function () { return port; } },
        "frontController": { get: function () { return frontController; } },
        "mainURL": { get: function () { return "localhost:"+port+"/"+frontController+"/"; } },
    });
};

var frontController = new ServerAPI(8080, "frontController");

frontController.mainURL; // returns "localhost:8080/frontController/"

This is new to es6, though most new browsers support it already. It eliminates that "this" and makes your controller object immutable. If you want, you can throw in setters, functions, whatever on this thing.

Just an FYI, console.log on a getter won't work well, it kind of stinks.
 
Cheers for that. Im still pretty new to javascript and getting my head around how it works. It took me so long just to figure out callbacks :$

Kinda miss Java now. Ive definitely developed an opinion on the whole strongly typed vs weakly typed thing that’s for sure...
 
Back
Top