简体   繁体   English

JS:构造函数内部的作用域

[英]JS: Scope Inside Constructor Function

I am new to OOP and I am trying to rewrite a simple JS function as an object literal and then as a constructor function. 我是OOP的新手,我试图将一个简单的JS函数重写为对象文字,然后再重写为构造函数。 I succeeded in writing the object literal version, but I clearly have a scope problem inside the anon function which handles the onclick event (inside my constructor function). 我成功地编写了对象文字版本,但是显然在处理onclick事件的anon函数内部(我的构造函数内部)存在范围问题。 Please let me know how to make the onclick event work. 请让我知道如何使onclick事件起作用。

Object Literal Version Which WORKS: 工作的对象文字版本:

var submit = {
    form_id : "",   
    submit_button_id : "",
    submit_form: function(){
        var button = document.getElementById(submit.submit_button_id);
        var form = document.getElementById(submit.form_id);     
        button.onclick = function(){
            form.submit();
            return false;
        }
    }
}

addLoadEvent(function(){
    submit.form_id = "form_vars";
    submit.submit_button_id = "but_submit";
    submit.submit_form();
});

Constructor Function Version Which DOESN'T WORK: 无效的构造函数版本:

function SubmitForm(button_id, form_id){
    this.submit_button = document.getElementById(button_id);
    this.form = document.getElementById(form_id);
    this.submit_form = function(){
        // problem function below
        this.submit_button.onclick = function(){
            this.form.submit();
        }
    }
}   

addLoadEvent(function(){
    var form_to_submit = new SubmitForm("but_submit", "form_vars");
    form_to_submit.submit_form();
});

PS I am aware that I should be using DOM API event handlers instead of HTML-DOM ones. PS我知道我应该使用DOM API事件处理程序,而不是HTML-DOM。 I am just tackling one thing at a time. 我一次只处理一件事。

this inside your function will not necessarily be the same as this in the constructor, it is decided by how you call that function. 函数内部的this不一定与构造函数中的this相同, this取决于您如何调用该函数。 For instance, if you call a function f by doing f() , then this === window , if it is a method on an object xf() then this === x . 例如,如果通过执行f()调用函数f ,则this === window ,如果它是对象xf()的方法,则this === x Also see Function:call and Function:apply . 另请参见Function:callFunction:apply

Simplest way to solve this is to have a local variable in the constructor (like var me = this; ) and then use me instead of this in the inner function, since that will not be overridden. 解决此问题的最简单方法是在构造函数中有一个局部变量(如var me = this; ),然后在内部函数中使用me代替this ,因为这不会被覆盖。

Read up on lexical scoping and closures if you want to learn more. 如果您想了解更多信息,请阅读词汇作用域和闭包。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM