前端框架封装(一)
jquery对外暴露了两个方法:jQuery和$,
* 这两方法实际上是同一个方法,
* 通过调用这两个方法,可以得到一个jQuery实例对象。
* jQuery实例对象是一个伪数组对象。
* jQuery和$实际上是一个工厂函数。
先实现一个弹出框插件的实列:(为了实现插件机制,让外界可以透过jQuery.fn扩充方法。)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 | <script> /* * jQuery插件实现机制: * 就是给原型添加一些功能方法。 * */ ( function ( w ) { // 对外暴露的工厂函数 function jQuery() { return new jQuery.fn.init(); } // 给原型提供一个简写方式 jQuery.fn = jQuery.prototype = { }; // init是jQuery中真正的构造函数 var init = jQuery.fn.init = function () { }; // 替换构造函数的原型 为 jQuery工厂的原型 init.prototype = jQuery.fn; // 把工厂通过两个变量暴露出去 w.jQuery = w.$ = jQuery; }( window )); // 实现一个jQ弹出框插件 jQuery.fn.alert = function ( msg ) { alert( msg ); }; // 测试插件 var $$ = $(); $$.alert( '弹出框插件' ); </script> |
Object.prototype.toString:
作用:根据内部的this返回一个类似于这样的字符串'[object constructorName]'
这个方法有个缺点,不能获取用户自定义对象的具体类型,只能获取内置对象的类型。
1 2 3 4 5 | //测试 console.log(Object.prototype.toString.call([])); console.log(Object.prototype.toString.call( new Date() )); console.log(Object.prototype.toString.call( Array )); console.log(Object.prototype.toString.call( Date )); |
简写 ==> 因为{}对象直接继承Object.prototype,
所以通过这个对象得到的toString,一定来自Object.prototype。
1 2 3 4 | console.log(({}).toString.call([])); console.log(({}).toString.call( new Date() )); console.log(({}).toString.call( Array )); console.log(({}).toString.call( Date )); |
用这个toString获取自定义对象的类型
1 2 3 | function Person(){} var xiaofang = new Person(); console.log(({}).toString.call( xiaofang )); |
代码块就是一对大括号。
1 2 3 4 | { var a = 1; console.log(a); } |
如果把一对大括号赋值给其他变量,或者参与运算,那么大括号就变成了字面对象。
1 | {}.toString(); //错误 |
需要通过运算,把{}转换为字面量,才能调用方法
1 | console.log(({}).toString()); |
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步