在面向对象javascript中传递函数作为参数
我对这一点很陌生,这反映在我的标题上 也许下面的例子能更好地说明我的问题 我有一个叫做模型的对象在面向对象javascript中传递函数作为参数,javascript,oop,object,Javascript,Oop,Object,我对这一点很陌生,这反映在我的标题上 也许下面的例子能更好地说明我的问题 我有一个叫做模型的对象 var Modal = new function(){ this.id = 'modal_id'; this.title = 'Modal title'; this.content = 'Modal content'; this.display = function(){ return '<div class="popup">' + thi
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>';
};
}
但是假设我想为按钮创建一个事件来触发不同的操作,当单击按钮时调用对象时,如何定义函数
$('#button').on('click', function(){
// different action here
});
有两件事你应该做,使这项工作最好
- 传入要分配的函数
- 返回一个真正的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"); });
函数
前面有一个不应该出现的新
。最后一个问题@Jememy,我可以知道如何调用函数的特定操作吗?比如Modal.close()?假设我在对象中定义了close函数。添加了一个调用示例。你真的应该看看这个。。。
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");
});