重新定义“this"在函数原型中并使用新参数运行它
Redefine "this" within a function prototype and run it with new parameters
我有一个从路径加载数据的函数原型。关键是我需要在之后改变路径。我试过调用、应用、绑定甚至分配,但由于我是新手,我没有找到解决方案。
下面是我的代码示例: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();
但是聊天容器继续从旧路径公开消息…
这看起来有点复杂。只需将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
看起来您正在使用loadMessages创建一个函数,这很好,但您需要传递一个值来设置新路径。你是这么想的吗?
Chat.prototype.loadMessages = function (newPath) {
this.messagesRef = newPath || this.database; // if newPath is empty than default to this.database
var setMessage = function(data) {
var val = data.val();
this.displayMessage(data.key, val.name, val.text);
};
var chat = new Chat
function setPath (newpath) {
chat.loadMessages(newpath);
}
相关文章:
- jquery设置为使用参数运行
- 如何用javascript替换Jquery字符串上的新参数
- 使用新参数通过服务器端处理重新绘制引导数据表
- 在页面加载完成之前,使用URL参数运行JavaScript
- 使用JavaScript中的参数运行.jar文件
- 使用Javascript从DB中筛选结果,这将使DIV重新加载它'基于新参数的内容
- Grunt为任务设置选项,并使用新值运行该任务
- 添加新参数到$resource后使用ngChange,Angular
- 根据窗口大小在 jQuery 滑块上调用新参数
- 是否可以通过添加新参数而不使用 eval 将所有这三个函数合并为一个函数
- 每天为每个新用户运行一次 JavaScript 函数
- 如何使用 javascript 中的参数运行 cmd.exe
- 如何使用参数运行函数
- 如何将新参数推入javascript'
- JS单元测试用不同的参数运行多次
- 用新参数重新加载页面
- 添加新参数以保证所有链
- 重新定义“this"在函数原型中并使用新参数运行它
- 如何带参数运行npm {bin: script.js}
- 调整Etherpad以对新参数作出反应