【问题标题】:function prototype call another function prototype javascript [duplicate]函数原型调用另一个函数原型javascript [重复]
【发布时间】:2018-06-12 11:24:22
【问题描述】:
function Chat() {
    // hander vent //
    // this.message_text.on("keyup click", this.saveMessage);
    $('.chat').on("click", this.init);
}

Chat.prototype.init = function() {
    var sef = this;
    this.hihi();
}
Chat.prototype.hihi = function() {
    return 2;
}

let chat = new Chat();

我在类类型原型中定义了两个方法。 但是当我在函数 init 中调用函数名 hihi 时。 当我使用 Chat 类型的 create 实例运行代码时。 它无法运行并显示错误。

TypeError: this.hihi is not a function at HTMLButtonElement.Chat.init (fotozidiqo.js:9:10)

如何在初始化函数名中调用这个函数。

【问题讨论】:

  • this.init.bind(this)

标签: javascript function-prototypes


【解决方案1】:

执行此操作时:$('.chat').on("click", this.init);,jQuery 将 init() 方法的 this 更改为从 $('.chat') 返回的元素。这就是为什么在 init 方法中调用 this.hihi(); 时它未定义的原因,因为它在 HTMLElement 上不存在。

所以为了得到正确的this,你必须像这样绑定Chat原型的this

function Chat() {
    $('.chat').on("click", this.init.bind(this));
}

如果你想调试这个,你可以在你的init()方法上console.log(this),你会看到HTMLElement

【讨论】:

  • 这不是范围问题。 this 不称为“范围”。
  • 你能建议我正确的解决方案吗
  • @tomnyson 改变这一点,$('.chat').on("click", this.init.bind(this)); 应该可以完成这项工作。
猜你喜欢
  • 1970-01-01
  • 2014-04-04
  • 2010-11-29
  • 2014-11-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多