简体   繁体   English

对象内的Javascript原型方法

[英]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;我正在尝试创建一个包含其他对象和函数的对象,在原型中,相关部分是 UI 原型;

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当我调用fChatInstance.UI.Login.Show()它给我一个错误: Uncaught TypeError: this.Log is not a function

Is that because by using this is on another scope?那是因为使用this是在另一个范围内吗? Usually i do var self = this;通常我做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.问题是this的javascript动态绑定,要修复它,您可以使用bind函数将“this”设置为对象。 Change the fchat function refactor it like this:像这样改变 fchat 函数重构它:

var fChat = function() {
  this.debug = true;
  this.UI.Login.Show =  this.UI.Login.Show.bind(this);
  this.Log =  this.Log.bind(this);
};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 在JavaScript类中调用父方法,但stll可以访问对象实例内部的原型方法吗? - Call parent method in JavaScript class but stll have access to prototype methods inside object instance? 使用原型对象向javascript对象添加自定义属性和方法的高级技巧 - Advatanges of using prototype object to add custom properties and methods to a javascript object 茉莉花无法在Javascript原型方法中运行规范 - Jasmine can't run specs inside Javascript prototype methods 在对象内部创建原型方法的缺点是什么? - What's the disadvantage of creating prototype methods inside the object? 在对象原型方法中的setInterval / setTimeout内部引用“ this” - Referencing “this” inside setInterval/setTimeout within object prototype methods 扩展Javascript原型方法 - Extending Javascript prototype methods 无法访问通过原型添加到Javascript对象的方法 - Can't access to methods that added via Prototype to Javascript object 在Javascript中向Object.prototype添加方法有什么好处和危险? - What are the benefits and dangers of adding methods to Object.prototype in Javascript? 使用 JavaScript 原型对象时事件方法中的“this”关键字 - "this" keyword in event methods when using JavaScript prototype object 通过Javascript中的原型访问Date对象的方法 - Accessing Date object's methods via prototype in Javascript
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM