打开一个模式窗口,对结果有两种处理方式,一种是用returnValue,另一种是传递一个对象给模式窗口,让模式窗口处理结果
父窗口:
<html> <head> <script language="javascript"> function callback(obj){ alert(obj.hi); } function opendialog1(){ window.showModalDialog('modalDialog.html',{callback:callback},''); } function opendialog2(){ var diaArgs = window.showModalDialog('modalDialog.html','',''); callback.apply(this,diaArgs); } </script> </head> <body> <button onclick="opendialog1();">打开模态窗口:传递对象给模式窗口调用</button> <button onclick="opendialog2();">打开模态窗口:获取模式窗口的returnValue</button> </body> </html>
模式窗口:
<html> <head> <script language="javascript"> function cback1(){ window.close(); window.dialogArguments.callback.apply(this,arguments); }; function cback2(){ window.returnValue=arguments; window.close(); }; </script> </head> <body> <button onclick="cback1({hi:'方式一:模式窗口调用了父类方法'})">方式一:调父类方法</button> <button onclick="cback2({hi:'方式二:使用了模式窗口的returnValue'})">方式二:使用returnValue</button> </body> </html>
这两种方式到底有什么优劣?方式二说起来更OO,但是想想方式一也未尝不可,就是一个方法调用另一个方法,并把一个回调函数传给它,在javascript里这种方式很常见啊,为什么说不好?说不好的能给个充足的理由吗?