【问题标题】:How to pass parameters to a function declared like left = function()如何将参数传递给声明为 left = function() 的函数
【发布时间】:2012-01-23 16:47:24
【问题描述】:

如何将参数传递给声明为 something = function(){};

的函数
window.prototype.initInterface = function(){
    this.mainPane = document.createElement('div');
    this.mainPane.style.border="5px solid grey";
    this.mainPane.style.margin="0px";
    this.mainPane.style.width="420px";
    this.mainPane.style.height="600px";

    this.exitButton = document.createElement('input');
    this.exitButton.setAttribute("type", "button");
    this.exitButton.setAttribute("value", "exit");

    this.exitButton.onclick = function(){
        document.body.removeChild(this.mainPane);
    };

    this.mainPane.appendChild(this.exitButton);

    document.body.appendChild(this.mainPane);
}

当用户按下退出按钮时,我想从 html 页面的正文中删除 mainPane。

    this.exitButton.onclick = function(this.mainPage){
        document.body.removeChild(this.mainPane);
    };

不工作

我该怎么做?

【问题讨论】:

  • window.prototype?我不认为window 是构造函数...
  • 谢谢,下面的工作: var self = this; this.exitButton.onclick = function(){ document.body.removeChild(self.mainPane); };

标签: javascript function parameters prototype


【解决方案1】:

为了让您的exitButton.onclick 函数能够访问您在封装initInterface 函数中创建的变量,您希望通过返回一个执行您想要的操作的函数并将其传递给exitButton.onclick 函数来创建一个闭包变量。

exitButton.onclick = function () {
    return (function() {
         document.body.removeChild(mainPane);
    })(mainPane);
};

阅读更多关于闭包如何工作的herehere 并查看工作中的example fiddle

或者,您可以忘记闭包并从触发事件的按钮向上走 DOM 到您的 mainPane

exitButton.onclick = function() {
   // in here "this" is the object that triggered the event, exitButton
   document.body.removeChild(this.parentNode);
}

顺便说一句,如果您在浏览器中执行此操作,window.prototype 不存在; window 是浏览器脚本中原型链顶部的对象。您只需要window.initInterface = function () {},它与function initInterface() {} 完全相同,因为您在浏览器中的javascript 中所做的一切都会成为window 的属性。

【讨论】:

    【解决方案2】:

    这个函数是没有函数名的函数。它只能使用一次,您可能不容易找出应该传递哪些参数。

    你可以创建另一个函数,比如:

    函数 go(a1){}

    并像 window.prototype.initInterface = go(a1); 一样调用它

    或者你可以通过getDocumentById("DOM ID")等函数在这个未命名的函数中获取一些DOM参数。

    【讨论】:

    • 这是不正确的。第一个 function go(var a1){} 不是有效的 JavaScript。其次,函数不需要名称即可在调用时向其传递参数:var foo = function(bar) {...}。混淆更多的是关于定义一个函数并调用它。在OP的代码中,他是定义一个函数,所以每个参数名称必须遵循一定的规则,例如名称不能包含.
    • 感谢指正!我的错。我仍然建议使用一些名称可以重复使用的函数,并且更好地找出应该传递哪些参数。
    猜你喜欢
    • 2017-10-24
    • 2019-01-28
    • 1970-01-01
    • 2013-01-27
    • 1970-01-01
    • 1970-01-01
    • 2016-12-20
    • 2022-01-10
    • 1970-01-01
    相关资源
    最近更新 更多