2

I'm trying to create an Object containing other Objects and functions, in a prototype, the relevant part is the UI prototype;

var fChat = function() {
    this.debug = true;
};

fChat.prototype = {
    constructor: fChat,
    Log: function(str){
        if(this.debug){
            console.log(str);
        }
    },
    UI: {
        Login: {
            Show: function(){
                this.Log("UI.Login.Show()");
            }
        }           
    }
};

var fChatInstance = new fChat();
fChatInstance.UI.Login.Show();

When i call fChatInstance.UI.Login.Show() It give me an error: Uncaught TypeError: this.Log is not a function

Is that because by using this is on another scope? Usually i do var self = this;at the start of a prototype, but i don't know how I can do that by using an Object prototype.

5
  • this is the object { Show: function() { /*...*/ } }. You can figure that out by debugging within Show and checking this or by doing console.log(this); within Show Commented Jul 3, 2015 at 14:22
  • 1
    This is a bit of a strange pattern. So each fChat has it's own singletons of Log, UI? Seems like all of that stuff should be abstracted out into their own unit-of-work "classes" Commented Jul 3, 2015 at 14:25
  • @RGraham it is the first time i use prototypes and "classes", so i can do it in a wrong way. Anyway i initialize only one instance of fChat. Commented Jul 3, 2015 at 14:28
  • 1
    I agree with @RGraham that it's better to split this "class" up into multiple classes. For example, create a Login class and then pass in a Logger class instance in the constructor. Right now that fChat class has multiple responsibilities. Commented Jul 3, 2015 at 14:28
  • Checkout You Don't Know JS: this & Object Prototypes for some good information about this. Commented Jul 3, 2015 at 14:43

1 Answer 1

1

Yes. The problem is the javascript dynamic binding of this, to fix it you can set "this" to the object by using bind function. Change the fchat function refactor it like this:

var fChat = function() {
  this.debug = true;
  this.UI.Login.Show =  this.UI.Login.Show.bind(this);
  this.Log =  this.Log.bind(this);
};
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.