JavaScript实现链式调用
2024-10-18 18:15:26
学习Jquery的时候,我们通常会看到链式调用的写法
$(window).addEvent('load', function(){ $('test').show().setStyle('color', 'red').addEvent('click', function(e){ $(this).setStyle('color', 'yellow'); }); });
下面用JavaScript来实现一个链式调用,核心思想是借助原型构造函数,在每个方法中return this。
(function(){ function _$(els){ this.element = []; for(var i = 0, len = els.length; i < len; i++){ var element = els[i]; if(typeof element === 'string'){ element = document.getElementById(element); } this.element.push(element); } return this; } _$.prototype = { each: function(fn){ for(var i = 0, len = this.element.length; i < len; i++){ fn.call(this, this.element[i]); } return this; }, setStyle: function(prop, val){ this.each(function(el){ el.style[prop] = val; }); return this; }, show: function(){ var that = this; this.each(function(el){ that.setStyle('display', 'none'); }); return this; }, addEvent: function(type, fn){ var add = function(el){ if(window.addEventListener){ el.addEventListener(type, fn, false); }else if(window.attachEvent){ el.attachEvent('on' + type, fn); } }; this.each(function(el){ add(el); }); } }; window.$ = function(){ return new _$(arguments); } })();
下面用JavaScript来实现一个链式调用,核心思想是给Number对象原型添加属性和方法。
(10).add(10).reduce(2).add(10) Number.prototype.add = function(num){ return this+num; } Number.prototype.reduce = function(num){ return this-num; }
最新文章
- mysql 基础
- PHP安全编程:不要让不相关的人看到报错信息
- WP8_检测列表是否滑动
- SharedPreferences实现记住密码功能
- Drupal如何实现类的自动加载?
- 学java入门到精通,不得不看的15本书
- 集成对象和 JSON
- Codeforces739E Gosha is hunting
- Apple Swfit UI控件实现
- WebConfig 配置文件详解
- TextView于getCompoundDrawables()使用演示样本的方法
- 由ASP.NET所谓前台调用后台、后台调用前台想到HTTP
- service_names配置不正确,导致dg创建失败
- qrcode生成二维码
- String、StringBuffer、StringBuilder区别
- python之线程相关操作(补充)
- C# 中删除控件的事件的方法类
- 关于System.getProperty(";java.io.tmpdir";);的输出,及System.getProperty();参数
- PL/SQL编程1-基础
- C 标准库 - string.h之memcmp使用