【问题标题】:Not able to call a method by using 'this' keyword inside another method from a same class [duplicate]无法通过在同一类的另一个方法中使用“this”关键字来调用方法[重复]
【发布时间】:2016-06-03 16:08:44
【问题描述】:

我试图在用户提交表单后传递警报。 html是这样的

<form id="profile" name="profile">
  <label for="firstName">Male</label>
  <input type="text" name="firstname" id="firstName" maxlength="20" class="required" value=""/>
  <input type="submit" name="sumit" value="submit"/>
</form>

而JS是

var Form = function(){}; 

Form.prototype.formValidate = function($form){

    $form.on('submit', function(e){
    e.preventDefault();
    this.test()// this doesn't work
    //alert('t') // this works
  })

}

Form.prototype.test = function(){
    alert('t');
}
var form = new Form();
form.formValidate($('#profile'))

当我收到一条错误消息说 ..this.test 不是函数时... 如果我只是在 e.preventDefault() 之后通过警报但它不能调用我不能通过关键字“this”调用方法。这让我说我的范围不对。我错过了什么?

【问题讨论】:

    标签: javascript jquery


    【解决方案1】:

    在 JavaScript 中,this 的值是基于作用域的。每次你有function(){},那么你就有一个 new 作用域。在每个函数内部,this 会有所不同,它是根据该函数的调用方式来设置的。

    你在哪里this.test()this 不是Form 对象,它是#profile 元素。您需要将 this 值保存到变量中,以便在事件中使用它。

    Form.prototype.formValidate = function($form){
        var self = this;
    
        $form.on('submit', function(e){
            e.preventDefault();
            self.test();
        });
    };
    

    【讨论】:

    • 对..我可以在 $form.on() 之外调用它
    • @soum:没错,因为那时你在Form 对象的一个​​函数中。进入活动后,您将处于新的环境中,this 已更改。这就是为什么您需要将其保存为变量,然后在事件中访问该变量。
    猜你喜欢
    • 1970-01-01
    • 2018-05-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-01-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多