<script type="text/javascript"> function Person(){ this.name='li4' this.age=20 this.eat=function(){console.log('eating ...')} this.sing=function(){console.log('sing ...')} } var p1=new Person() console.log('my name is '+p1.name+', i am '+p1.age) p1.eat() p1.sing() //设计模式:简单的链式编程, //调用return this function Man(){ this.name='w5' this.age=24 this.eat=function(){console.log('包子、油条 ...');return this;} this.work=function(){console.log('coding ...');return this;} this.sleep=function(){console.log('z Z Z...');return this;} } var m=new Man() m.eat().work().sleep() </script>
# 模拟jquery <body> <input type="button" id="inp" value='按钮'/> <script type="text/javascript"> (function(window,undefined){ //$为外部最常用的方法,大型程序开发中,下划线_作为私有的对象 function _$(arguments){ var id_reg=/#\w+/ //接受匹配到的元素 //this.dom if(id_reg.test(arguments[0])){ this.dom=document.getElementById(arguments[0].substring(1)) }else{ throw new Error(' argument must be given with #!') } } //在Function类上扩展一个可以实现链式编程的方法 Function.prototype.method=function(methodName,fn){ this.prototype[methodName]=fn return this } //在_$对象上,增加一些公共方法 _$.prototype={ constructor:_$, add:function(type,fn){ //给你得到元素,注册事件 if(window.addEventListener){ console.log(this.dom) this.dom.addEventListener(type,fn) }else if(window.attachEvent){ this.dom.attachEvent('on'+type,fn) } return this }, set:function(prop,val){ this.dom.style[prop]=val return this } } //window上注册一个全局变量,可以调用_$内置的方法,与外界产生关系; window.$=_$ //onReady方法用于先实例化_$对象,再注册到window上 _$.onReady=function(fn){ window.$=function(){ return new _$(arguments) } //执行传入的代码 fn() //实现链式编程 _$.method('add',function(){}).method('set',function(){}) } })(window) $.onReady(function(){ console.log($('#inp').dom.nodeName) $('#inp').set('click',function(){alert('click ...')}) }) </script> </body>
转载于:https://blog.51cto.com/f1yinsky/1954284