javascript里的单例模式,单例模式的好处就不做介绍了,只是写出js的单例写法!
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>JS单例模式</title> <style type="text/css"> div{height:100px; width:100px; background:#CCC; border:#000 1px solid;} </style> <script type="text/javascript"> my = new function yangbin() { this.name = "我是单例funnyzak!"; }; function yangbin1(){ this.name = "我是funnyzak!"; } function myname(){ var u = new yangbin1(); alert(u.name); } </script> </head> <body> <div onclick="alert(my.name);">你是?(单例)</div> <div onclick="myname();">你是?(普通)</div> </body> </html>
运行代码