【问题标题】:Pass function as parameter in object oriented javascript在面向对象的javascript中将函数作为参数传递
【发布时间】:2014-10-07 01:45:30
【问题描述】:

我对此很陌生,这反映在我放置标题的方式上。

也许下面的例子可以更好地说明我的问题。

我有一个名为模型的对象。

var Modal = new function(){
    this.id = 'modal_id';
    this.title = 'Modal title';
    this.content = 'Modal content';
    this.display = function(){
        return '<div class="popup">' + this.title + ' ' + this.content + '<br><button id="button"></div>';
    };
}

这个对象是这样调用的,例如:

Modal.title = 'My New title';
Modal.content = 'My New content';
Modal.display();

但是假设我想为按钮设置一个事件来触发不同的操作,当单击按钮时调用对象时如何定义函数?

$('#button').on('click', function(){
    // different action here
});

【问题讨论】:

  • 点击时你想调用什么?模态显示()?
  • 可以是任何动作。但我想要这样一种方式,我可以对该点击进行自定义操作,并且可以在调用它时进行定义。一个 Modal 可以触发动作 A,而另一个 Modal 可以在单击按钮时触发另一个不同的动作。
  • 你能给我一个正当的理由吗? @Bergi
  • @davidlee:请阅读我链接到的问题的答案。如果您对我在那里给出的理由有任何异议,请在此处发表评论。

标签: javascript oop object


【解决方案1】:

您应该做两件事来使这项工作达到最佳效果。

  • 传入要分配的函数
  • 返回一个真正的 DOM 元素,而不是用字符串构建 HTML。

    var Modal = function(onClickHandler){
      this.id = 'modal_id';
      this.title = 'Modal title';
      this.content = 'Modal content';
      this.display = function(){
          var div = document.createElement("div");
          div.className = "popup";
          div.appendChild(document.createTextNode(this.title));
          div.appendChild(document.createTextNode(" "));
          div.appendChild(document.createTextNode(this.content));
          div.appendChild(document.createElement("br");
    
          var button = document.createElement("button");
          // Assign a unique ID here if you need.
    
          // You could also use addEventListener as well
          button.onclick = onClickHandler;
          button.appendChild(document.createTextNode("CLICK!"));
    
    
          div.appendChild(button);
          return div;
      };
    }
    
    Modal.prototype.close = function(){
      console.log("Close it");
      console.log(this);
    }
    
    
    var newDiv = new Modal(function() {
      alert("I was clicked");
    });
    

【讨论】:

  • 如何用函数调用对象?
  • 它有这个错误:TypeError: Modal is not a constructor
  • 抱歉,打错了.. new 前面有一个不应该出现的 new
  • 最后一个问题@Jememy,我可以知道如何通过函数调用特定操作吗?像 Modal.close()?前提是我在对象中定义了关闭函数。
  • 添加了调用示例。你真的应该读这个...stackoverflow.com/questions/1809914/…
猜你喜欢
  • 2018-02-23
  • 2012-05-30
  • 1970-01-01
  • 2012-06-12
  • 1970-01-01
  • 2019-08-29
  • 2012-03-07
  • 2014-06-07
  • 1970-01-01
相关资源
最近更新 更多