front end :js,package 封装

本文介绍了三种JavaScript中的封装方法:使用约定优先原则、严格实现封装及利用闭包方式。每种方法都有详细示例代码,帮助读者理解如何在JS中实现封装。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

转载请标明出处:http://blog.youkuaiyun.com/lmj623565791/article/details/25080573

js中处处是对象,面向对象的第一步当然就是封装了,由于Js中没有类的概念,所以封装起来也比较麻烦,下面介绍两种js的封装。

1、使用约定优先的原则,将所有的私有变量以_开头

[javascript] view plain copy
  1. <script type="text/javascript">  
  2.        /** 
  3.         * 使用约定优先的原则,把所有的私有变量都使用_开头 
  4.         */  
  5.        var Person = function (no, name, age)  
  6.        {  
  7.            this.setNo(no);  
  8.            this.setName(name);  
  9.            this.setAge(age);  
  10.        }  
  11.        Person.prototype = {  
  12.            constructor: Person,  
  13.            checkNo: function (no)  
  14.            {  
  15.                if (!no.constructor == "string" || no.length != 4)  
  16.                    throw new Error("学号必须为4位");  
  17.            },  
  18.            setNo: function (no)  
  19.            {  
  20.                this.checkNo(no);  
  21.                this._no = no;  
  22.            }, getNo: function ()  
  23.            {  
  24.                return this._no;  
  25.            }, setName: function (name)  
  26.            {  
  27.                this._name = name;  
  28.            }, getName: function ()  
  29.            {  
  30.                return this._name;  
  31.            }, setAge: function (age)  
  32.            {  
  33.                this._age = age;  
  34.            }, getAge: function ()  
  35.            {  
  36.                return this._age;  
  37.            }, toString: function ()  
  38.            {  
  39.                return "no = " + this._no + " , name = " + this._name + " , age = " + this._age;  
  40.            }  
  41.        };  
  42.        var p1 = new Person("0001""鸿洋""22");  
  43.        console.log(p1.toString());        //no = 0001 , name = 鸿洋 , age = 22  
  44.        p1.setNo("0003");  
  45.        console.log(p1.toString());      //no = 0003 , name = 鸿洋 , age = 22  
  46.        p1.no = "0004";  
  47.        p1._no = "0004";  
  48.        console.log(p1.toString());    //no = 0004 , name = 鸿洋 , age = 22  
  49.   
  50.    </script>  

看完代码,是不是有种被坑的感觉,仅仅把所有的变量以_开头,其实还是可以直接访问的,这能叫封装么,当然了,说了是约定优先嘛,这种方式还是不错的,最起码成员变量的getter,setter方法都是prototype中,并非存在对象中,总体来说还是个不错的选择。如果你觉得,这不行,必须严格实现封装,那么看第二种方式。

2、严格实现封装

[javascript] view plain copy
  1. <script type="text/javascript">  
  2.         /** 
  3.          *  使用这种方式虽然可以严格实现封装,但是带来的问题是get和set方法都不能存储在prototype中,都是存储在对象中的 
  4.          * 这样无形中就增加了开销 
  5.          */  
  6.         var Person = function (no, name, age)  
  7.         {  
  8.             var _no , _name, _age ;  
  9.             var checkNo = function (no)  
  10.             {  
  11.                 if (!no.constructor == "string" || no.length != 4)  
  12.                     throw new Error("学号必须为4位");  
  13.             };  
  14.             this.setNo = function (no)  
  15.             {  
  16.                 checkNo(no);  
  17.                 _no = no;  
  18.             };  
  19.             this.getNo = function ()  
  20.             {  
  21.                 return _no;  
  22.             }  
  23.             this.setName = function (name)  
  24.             {  
  25.                _name = name;  
  26.             }  
  27.   
  28.             this.getName = function ()  
  29.             {  
  30.                 return _name;  
  31.             }  
  32.   
  33.             this.setAge = function (age)  
  34.             {  
  35.                 _age = age;  
  36.             }  
  37.             this.  
  38.                     getAge = function ()  
  39.             {  
  40.                 return _age;  
  41.             }  
  42.   
  43.             this.setNo(no);  
  44.             this.setName(name);  
  45.             this.setAge(age);  
  46.         }  
  47.         Person.prototype = {  
  48.             constructor: Person,  
  49.             toString: function ()  
  50.             {  
  51.                 return "no = " + this.getNo() + " , name = " + this.getName() + " , age = " + this.getAge();  
  52.             }  
  53.         }  
  54.         ;  
  55.         var p1 = new Person("0001""鸿洋""22");  
  56.         console.log(p1.toString());        //no = 0001 , name = 鸿洋 , age = 22  
  57.         p1.setNo("0003");  
  58.         console.log(p1.toString());      //no = 0003 , name = 鸿洋 , age = 22  
  59.         p1.no = "0004";  
  60.         console.log(p1.toString());    //no = 0003 , name = 鸿洋 , age = 22  
  61.   
  62.     </script>  

看上面的代码,去掉了this.属性名,严格的实现了封装,只能通过getter,setter访问成员变量了,但是存在一个问题,所有的方法都存在对象中,增加了内存的开销。

3、以闭包的方式封装

[javascript] view plain copy
  1. <script type="text/javascript">  
  2.         /** 
  3.          *  使用这种方式虽然可以严格实现封装,但是带来的问题是get和set方法都不能存储在prototype中,都是存储在对象中的 
  4.          * 这样无形中就增加了开销 
  5.          */  
  6.         var Person = (function ()  
  7.         {  
  8.             var checkNo = function (no)  
  9.             {  
  10.                 if (!no.constructor == "string" || no.length != 4)  
  11.                     throw new Error("学号必须为4位");  
  12.             };  
  13.             //共享变量  
  14.             var times = 0;  
  15.   
  16.             return function (no, name, age)  
  17.             {  
  18.                 console.log(times++);    // 0 ,1 , 2  
  19.                 var no , name , age;  
  20.                 this.setNo = function (no)  
  21.                 {  
  22.                     checkNo(no);  
  23.                     this._no = no;  
  24.                 };  
  25.                 this.getNo = function ()  
  26.                 {  
  27.                     return this._no;  
  28.                 }  
  29.                 this.setName = function (name)  
  30.                 {  
  31.                     this._name = name;  
  32.                 }  
  33.   
  34.                 this.getName = function ()  
  35.                 {  
  36.                     return this._name;  
  37.                 }  
  38.   
  39.                 this.setAge = function (age)  
  40.                 {  
  41.                     this._age = age;  
  42.                 }  
  43.                 this.  
  44.                         getAge = function ()  
  45.                 {  
  46.                     return this._age;  
  47.                 }  
  48.   
  49.                 this.setNo(no);  
  50.                 this.setName(name);  
  51.                 this.setAge(age);  
  52.             }  
  53.         })();  
  54.         Person.prototype = {  
  55.             constructor: Person,  
  56.             toString: function ()  
  57.             {  
  58.                 return "no = " + this._no + " , name = " + this._name + " , age = " + this._age;  
  59.             }  
  60.         }  
  61.         ;  
  62.         var p1 = new Person("0001""鸿洋""22");  
  63.         var p2 = new Person("0002""abc""23");  
  64.         var p3 = new Person("0003""aobama""24");  
  65.   
  66.   
  67.         console.log(p1.toString());        //no = 0001 , name = 鸿洋 , age = 22  
  68.         console.log(p2.toString());      //no = 0002 , name = abc , age = 23  
  69.         console.log(p3.toString());    //no = 0003 , name = aobama , age = 24  
  70.   
  71.     </script>  

上述代码,js引擎加载完后,会直接执行Student = 立即执行函数,然后此函数返回了一个子函数,这个子函数才是new Student所调用的构造函数,又因为子函数中保持了对立即执行函数中checkNo(no) ,times的引用,(很明显的闭包)所以对于checkNo和times,是所有Student对象所共有的,创建3个对象后,times分别为0,1,2 。这种方式的好处是,可以使Student中需要复用的方法和属性做到私有且对象间共享。


http://blog.youkuaiyun.com/Debug_feng/article/details/59122430

自己创建一个 JavaScript 库,虽然自己创建的可能没有那些开源 JavaScript 库功能强大,但在提升自己 JavaScript 开发能力,有很大帮助。
 创建基础库
我们可以创建一个库,这是一个基础库,名字就叫做 base.js。我们准备在里面编写最常
用的代码,然后不断的扩展封装。
在最常用的代码中,最常用的,也许就是获取节点方法。这里我们可以编写如下代码:
  //创建一个 base.js
  var Base = { //整个库是一个对象
         getId : function (id) { //方法名自己定义
         return document.getElementById(id);
  },
  getName : function (name) {
         return document.getElementsByName(name);
  },
  getTagName : function (tag) {
        return document.getElementsByTagName(tag);
  }

  };


  //html文件内容(简略)

<div id="box">id</div>
<input type="radio" name="sex" value="男" checked="checked" />
<p>段落</p>


  //前台调用代码
  window.onload = function () {
       alert(Base.getId('box').innerHTML);   //提示框显示 id
       alrt(Base.getName('sex')[0].value);   //提示框显示 男
       alert(Base.getTagName('div')[2].innerHTML);  //提示框显示 段落
  };


在一个JS文件中引用另一个JS文件

方法一,在调用文件的顶部加入下例代码:
document.write(” < script language = javascript src = / js /import .js’ >< / script>”);
(注:有时你引用的文件还可能需要引用其他的js,我们需要将需要的那个js文件也以同样的方法引用进来)

方法二,通过中间界面对js进行应用

就是我们可以在某个html中引用了你需要的js文件,我们可以通过拿到那个html文件的对象,然后在通过这个对象去引用js的方法。

(一般不常用,这个在我做项目的时候用过一次)

方法三:在将下边代码放入Body中:
new_element = document.createElement(”script”);
new_element.setAttribute(”type”,”text
/ javascript”);
new_element.setAttribute(”src”,”import .js”);
document.body.appendChild(new_element);
  我们来分析一下关键的几句代码:
  首先,我们利用document.createElement(”script”)生成了一个script的标签,设置其 type属性为text/javascript,src为import.js(这里的1.js同2.js放在同一个目录,也可放在不同的目录)。最后将这个标签动态 地加入body中。如此一来,我们就可以调用到不同js文件中的方法了。

  注意:<script language=”JAVASCRIPT” src=’1.js’></script>一定要放在body下面。
    因为在2.js中用到了body(document.body.appendChild(new_element);)
    如果将引如2.js的代码放在body上面,也就是说,
    进入页面后,还没有生成body就已经执行b.js里的document.body.appendChild(new_element);了。

    这时body不存在就会抛javascript错误。

(说明:从网上转载加了一些自己的总结和方法)


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值