- /*">
- <script>
- /**
- * 以下代码是参考 Jquery core.js 核心库文件仿写的 Circle 类 Demo 用例
- *
- */
- (function() {
- var Circle = (function() {
- // 定义一个构造函数
- var circle = function(radius) {
- return new circle.fn.init(radius);
- }, r;
- // 构建函数原型链
- circle.fn = circle.prototype = {
- constructor: circle,
- PI: 3.14,
- init: function(radius) {
- this.r = radius;
- },
- area: function() {
- return this.PI * this.r * this.r;
- }
- }
- // 最后指定 init 函数的原型
- circle.fn.init.prototype = circle.fn;
- // circle 的应用扩展接口
- circle.extend = circle.fn.extend = function() {
- var target = arguments[0] || {},
- length = arguments.length,
- i = 1;
- // 注意这段代码, 目的是当我们输入 $.fn.extend({name: 'Jack'}) 类似代码时,
- // 能够保证 name 属性挂载到 $.fn 上去
- if (length === i) {
- target = this;
- --i;
- }
- for(;i < length; i++) {
- var opt = arguments[i];
- for(var name in opt) {
- var copy = opt[name];
- if (target[name] == copy) continue;
- target[name] = copy;
- }
- }
- return target;
- }
- // 扩展一个函数试试!!
- circle.fn.extend({
- getRadius: function() {
- return this.r;
- }
- });
- return circle;
- })();
- // 将 Circle 挂载到 window
- window.$ = Circle;
- })();
- // 基础测试
- /*
- document.write($);
- document.write('<br />');
- document.write($(3));
- document.write('<br />');
- document.write($(3).area());
- */
- // 扩展测试
- $.fn.extend({Name: 'Jack'});
- /*
- document.write('Hi,输入的半径值:'+$(3).getRadius());
- document.write('<br />');
- document.write('Hi, 扩展进来的值:'+$().Name);
- document.write('<br />');
- */
- // 检查原型链上的参数
- var c = $(3);
- for (var m in c) {
- if (c.hasOwnProperty(m))
- document.write('实例属性: '+m+'<br />');
- else
- document.write('类属性: '+m+'<br />');
- }
- </script>
- //该片段来自于http://www.codesnippet.cn/detail/201120137319.html
来源: http://www.codesnippet.cn/detail/201120137319.html