var Factory = function(type,content){ if (this instanceof Factory) { var s = new this[type](type,content);//运算符优先顺序 return s; }else { return new Factory(type,content); } } Factory.prototype = { html:function(type,content){ this.content = content; this.type = type; this.show = function(){ console.log(this.type+this.content); } }, php:function(type,content){ this.content = content; this.type = type; this.show = function(){ console.log(this.type+this.content); } } } var p1 = Factory('html','哪家强?'); p1.show(); var p2 = Factory('php','真的不错!'); p2.show();
三个不同功能的按钮
<body> <input type='button' value='btn1' name='click'/> <input type='button' value='btn2' name='mouseover'/> <input type='button' value='btn3' name='dblclick'/> <div id='div1'></div> <script> var Factory = function(type,element){ if (this instanceof Factory) { var s = new this[type](element); return s; }else { return new Factory(type,element); } } Factory.prototype = { click:function(element){ element.addEventListener('click',function(){ oDiv.innerHTML = this.value; },false); }, mouseover:function(element){ element.addEventListener('mouseover',function(){ oDiv.innerHTML = this.value; },false); }, dblclick:function(element){ element.addEventListener('dblclick',function(){ oDiv.innerHTML = this.value; },false); } } var aBtn = document.getElementsByTagName('input'), oDiv = document.getElementById('div1'); for (var i=0;i<aBtn.length ;i++ ) { Factory(aBtn[i].name,aBtn[i]); } </script> </body>