-1

I have this object and i want to print its value to the console:

var PageStatistics = function (page) {
 var myFunctionName = function ()
    {
      //some logic of operation

      //i want to print to the console the current object state to see if my logic works
      console.log(this);
    }
}

but when looking at the console i see a "window" with all window's details, instead of object of PageStatistics.

How can i return the current instance of PageStatistics ?

Update: Added some real code This code gets response from a Facebook API query to calculate some statistics about a page's behaviour:

var PageStatistics = function (page) {
    var numberOfPosts = 0;
    var numberOfLikes = 0;
    var numberOfComments = 0;
    var numberOfShares = 0;
    var bestPostId = 0;
    var bestPostLikes = 0;
    var bestPostComments = 0;
    var bestPostShares = 0;
    var bestPostTotalEngagement = 0;

    this.onFacebookDataLoaded = function (posts) {
        var data = posts["data"];
        console.log(posts);
        for (var i = 0; i < data.length; i++) {
            var post = data[i];
            var postIds = post["id"].split("_");
            var postId = postIds[1];
            //TODO add feature for excluding array of posts

            numberOfPosts++;
            var likes = 0;
            var comments = 0;
            var shares = 0;
            if (isVariableExists(post["likes"]) && isVariableExists(post["likes"]["summary"]) && isVariableExists(post["likes"]["summary"]["total_count"]))
                likes = post["likes"]["summary"]["total_count"];
            if (isVariableExists(post["comments"]) && isVariableExists(post["comments"]["summary"]) && isVariableExists(post["comments"]["summary"]["total_count"]))
                comments =post["comments"]["summary"]["total_count"];
            if (isVariableExists(post["shares"]) && isVariableExists(post["shares"]["count"]))
                shares = post["shares"]["count"];
            numberOfLikes += likes;
            numberOfComments += comments;
            numberOfShares += shares;
            totalEngagement = likes + comments + shares;
            if (bestPostTotalEngagement < totalEngagement)
            {
                bestPostId = post["id"];
                bestPostLikes = likes;
                bestPostComments = comments;
                bestPostShares = shares;
                bestPostTotalEngagement = totalEngagement;
            }
        }
        //if the results have a next page - set the path to take it from there
        if (isVariableExists(posts["paging"]) && isVariableExists(posts["paging"]["next"]))
        {
            var next = posts["paging"]["next"];
            var pos = next.indexOf("/posts");
            var path = page.id + next.substr(pos);
            //Here is need to send another function my instance to continue to update it
            FacebookManager.getPageStatistics(page,this,path);
        }
       //here i want to check what we have gathered so far.
        console.log(this);
    }

    /**
     * Check if a variable exists
     * @param variable the variable to check
     * @returns {boolean} true if exists, false otherwise
     */
    var isVariableExists = function (variable) {
        if (typeof variable !== 'undefined')
            return true;
        return false;
    }

}
Asaf Nevo
  • 11,338
  • 23
  • 79
  • 154
  • show more code - at ur context this == window, we need ur events for helping u – Legendary Apr 01 '15 at 14:23
  • Try: `PageStatistics.prototype.myFunctionName() { return this; }` – Mr. Polywhirl Apr 01 '15 at 14:23
  • I don't feel this is a duplicate. Yes, the reason the original code doesn't work *is* the answer to that other question, but *this particular question* is asking *how to do it properly* and not *why it doesn't work*. – Darkhogg Apr 01 '15 at 14:26
  • Assuming that you created the instance with new like `new PageStatistics(...)` you can catch the new instance inside the `PageStatistics` function with something like self, e.g. `var self = this` and use in any private function you have, e.g. `var myFunctionName = function () { return self }` or you can call myFunctionName with the scope you want it to have e.g. `myFunctionName.call(self)` – Mauricio Poppe Apr 01 '15 at 14:30
  • I've added some code. @MauricioPoppe i'm checking to see if it works – Asaf Nevo Apr 01 '15 at 14:43
  • @MauricioPoppe that actually works. I must say it doesn't make sense to me that this kind of regular behaviour needs this tweak, but probably because i'm coming from OOP languages i'm just having hard time to get used to JS.. post it as an answer so I could accept it – Asaf Nevo Apr 01 '15 at 14:44
  • 1
    The question was marked as duplicated and I can't do that, anyways I'd recommend you to read http://eloquentjavascript.net/ and http://www.amazon.com/Professional-JavaScript-Developers-Nicholas-Zakas/dp/1118026691, those book helped me learn scope related stuff :) – Mauricio Poppe Apr 01 '15 at 19:44

2 Answers2

1

I think you are looking for somethink

    var PageStatistics = function (page) {
    this.myVariableName = '';
    var mySecondVariable = '';
    this.myFunctionName = function ()
    {
        //some logic of operation
        this.myVariableName = 'something';
        mySecondVariable = 'second something';
        //now this will return refrence of myVariableName variable and myFunctionName function, not of mySecondVariable
        console.log(this);
    }
}

var test = new PageStatistics();
test.myFunctionName();
  • i need to use the reference of my object inside my object instace – Asaf Nevo Apr 01 '15 at 14:32
  • You can't get refrence of your private variables like var post = data[i]; var postIds = post["id"].split("_"); var postId = postIds[1]; By using this If you still like to check what you have added with your variables then you need to add them with this like this.post = data[i]; this.postIds = post["id"].split("_"); this.postId = postIds[1]; Now you can get it by using console.log(this); – Abhishek Mishra Apr 02 '15 at 05:55
0

Create your function, then instantiate it.

Like this:

var PageStatistics = function () {
    this.myFunctionName = function (){
      console.log(this);
    }
}
var ps = new PageStatistics;
console.log(ps.myFunctionName); // myFunctionName
ps.myFunctionName.call(ps); // PageStatistics 
rjmacarthy
  • 2,164
  • 1
  • 13
  • 22