在函数原型中重新定义“this”并使用新参数运行它

时间:2016-08-26 21:40:24

标签: javascript prototype this call bind

我有一个从路径加载数据的函数原型。诀窍是我需要改变之后的路径。我尝试过调用,应用,绑定甚至分配,但由于我是新手,我没有找到解决方案。

这是我的代码示例:

Chat.prototype.loadMessages = function() {

    this.messagesRef = this.database;

    var setMessage = function(data) {
    var val = data.val();
    this.displayMessage(data.key, val.name, val.text);
    }.bind(this);

};

var chat = new Chat
function setPath (newpath) {
chat.loadMessages.messageRef = newpath; // I guess, it is where I'm wrong...
chat.loadMessages(); // It should load messages from the new path in my chat container.
}

正如我所说,我也尝试过:

chat.loadMessages.call(newpath);

 var setPath = function(newpath) {
      chat.loadMessages(newpath);
      }.bind(chat);
      setPath();
 chat.loadMessages();

但聊天容器继续披露来自旧路径的消息......

2 个答案:

答案 0 :(得分:1)

这看起来有点令人费解。只需将messagesRef作为参数传递,并将其默认为this.database

Chat.prototype.loadMessages = function(messagesRef = this.database) {
    // do whatever is needed with messagesRef
};

chat = new Chat();
chat.loadMessages(); // load from the default location
chat.loadMessages('foobar'); // load from this specific location

答案 1 :(得分:0)

看起来您正在使用 loadMessages 创建一个函数,这很好,但您需要传入一个值来设置新路径。这更像你在想什么?

- (void)viewWillAppear:(BOOL)animated{
    self.preferredContentSize = CGSizeMake(0, 100);
}