简体   繁体   中英

Javascript prototype Methods inside object

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.

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);
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM