【问题标题】:"this" changes value on click“this”在点击时改变值
【发布时间】:2016-11-15 20:17:02
【问题描述】:

如果我有以下代码:

function Something() {
    this.randomElement = $("#element");
}

Something.prototype = {

    functionOne: function() {
        console.log("hello");
    },

    functionTwo: function() {
        this.randomElement.click(function(e) {
            this.functionOne(); //this becomes pointed at randomElement
        });
    }
}

如何以简洁的方式编写此代码,而不必在 functionTwo 中使用 Something.prototype.functionOne() 替换 this.functionOne()?既然点击事件改变了this的值?

【问题讨论】:

    标签: javascript jquery prototype-programming


    【解决方案1】:

    因为this 绑定到被点击的项目。你需要使用bind

    this.randomElement.click( this.functionOne.bind(this) ); 
    

    或 jQuery 的 proxy

    this.randomElement.click( $.proxy(this.functionOne, this) ); 
    

    【讨论】:

      猜你喜欢
      • 2022-06-14
      • 1970-01-01
      • 2018-01-05
      • 2017-02-20
      • 1970-01-01
      • 2014-03-30
      • 2014-03-22
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多