原文地址:

http://frugalcoder.us/post/2010/02/11/js-classes.aspx

Classy JavaScript - Best Practices

11. February 2010 13:26

Okay, so you really want to be able to have some of your JavaScript methods to have access to a variable that is private, but maintains state between calls. The first piece of knowledge, is that you can have the contents of a function execute itself at runtime.

1.(function(){ /*Your actions here*/ })();

This is a very common method of defining complex classes and libraries, that can have their own variables or methods that aren't otherwise available to the object model outside this closure. When you utilize "this" within the function's closure it will be default to the global object, which in the Browser DOM is "window".

1.(function(){
2.this.test = "Test Value";
3.})();
4.alert(test); //alerts "Test Value"

Usually when creating libraries in JavaScript it's a good idea to create namespaces for your library. Below I am going to use a classic example for defining a namespace of My.Namespace. There are helper methods out there that will walk a chain from a literal string of "My.Namespace", but I'm showing it in raw script.

1.if (typeof My == 'undefined')
2.My = {};
3.if (typeof My.Namespace == 'undefined')
4.My.Namespace = {};

By combining the above method, and using the Function.prototype.call method on your anonymous function, you can call the function with "this" set to your namespace. I'll be implementing a class called "SomeClass" within "My.Namespace" below. I'll also be showing how to create private static members and methods, allong with public static methods, and instance methods.

01.//begin private closure
02.(function(){
03. 
04.//this is a private static member that is only available in this closure
05.var instances = 0;
06. 
07.//this is a private static method that can be used internally
08.function _incrementInstances() {
09.instances++;
10.}
11. 
12.//Define SomeClass (js uses functions as class constructors, utilized with the "new" keyword)
13.this.SomeClass = function(options) {
14.//if the function is called directly, return an instance of SomeClass
15.if (!(this instanceOf SomeClass))
16.return new SomeClass(options);
17. 
18.//call static method
19._doSomething();
20. 
21.//handle the options initialization here
22.}
23. 
24.//create a public static method for SomeClass
25.this.SomeClass.getInstanceCount = function() {
26.return instances; //returns the private static member value
27.}
28. 
29.//create an instance method for SomeClass
30.this.SomeClass.prototype.doSomething = function() {
31./*Do Something Here*/
32.}
33. 
34.//end private closure then run the closure, localized to My.Namespace
35.}).call(My.Namespace);

The above is an example of best practices for defining a Class within a given namespace. From here, you can instantiate an instance of "My.NameSpace.SomeClass" and utilize the public methods exposed.

01.//instantiate a SomeClass instance
02.var sc = new My.Namespace.SomeClass({/* options go here */});
03. 
04.//call SomeClass as a function, which will return an instance
05.//  defined above via "(!(this instanceOf SomeClass))"
06.var sc = My.Namespace.SomeClass({/* options */});
07. 
08.//view the instance count, which uses a public static method
09.//  to return a private static member.
10.alert(My.Namespace.SomeClass.getInstanceCoun());

From here, you may be thinking to yourself, that's a lot of typing. This is where aliasing can come in handy, in this example inside a closure of course.

01.(function(){
02.//alias My.NameSpace
03.var m = My.NameSpace
04. 
05.//bad form assigning onload internally,
06.//  but that'll be for another post on event binding
07.//  Also, we could use "this.onload" but using window directly is more obvious here.
08.window.onload = function() {
09.//attach an instance of My.NameSpace.SomeClass instance to window.
10.window.sc = new m.SomeClass({}); //no long namespace name here :)
11.}
12. 
13.})();

Hopefully this post will be helpful in utilizing some privacy with your classes, and using namespaces to prevent naming collisions with other classes, and libraries.

javascript 私有方法的实现的更多相关文章

  1. JavaScript 类私有方法的实现

    一:将私有方法移出模块,因为模块内部的所有方法都是对外可见的. class Widget { foo (baz) { bar.call(this, baz); } // ... } function ...

  2. JavaScript中子类调用父类方法的实现

    一.前言 最近在项目中,前端框架使用JavaScript面向对象编程,遇到了诸多问题,其中最典型的问题就是子类调用父类(super class)同名方法,也就是如C#中子类中调用父类函数base.** ...

  3. JavaScript内置一些方法的实现原理--new关键字,call/apply/bind方法--实现

    先学习下new操作符吧 new关键字调用函数的心路历程: 1.创建一个新对象 2.将函数的作用域赋给新对象(this就指向这个对象) 3.执行函数中的代码 4.返回这个对象 根据这个的思路,来实现一个 ...

  4. Atitit paip.对象方法的实现原理与本质.txt

    Atitit paip.对象方法的实现原理与本质.txt 对象方法是如何实现的1 数组,对象,字典1 对象方法是如何实现的 这显然是一个对象方法调用.但对象方法是如何实现的呢?在静态语言中,因为有编译 ...

  5. OC:属性的内部实现原理、dealloc内释放实例变量、便利构造器方法的实现原理、collection的内存管理

    代码: // // main.m #import <Foundation/Foundation.h> #import "Person.h" #import " ...

  6. 基于原生JS的jsonp方法的实现

    基于原生JS的jsonp方法的实现 jsonp,相信大家并不陌生,是在js异步请求中解决跨域的方法之一,原理很简单,有不清楚的同学可以google下,这里就补详细解释了.在Jquery库中,jQuer ...

  7. 关于Java中hashCode方法的实现源码

    首先来看一下String中hashCode方法的实现源码. public int hashCode() { int h = hash; if (h == 0 && value.leng ...

  8. js中的bind方法的实现方法

    js中目前我遇见的改变作用域的5中方法:call, apply, eval, with, bind. var obj = { color: 'green' } function demo () { c ...

  9. Salesforce LWC学习(十五) Async 以及 Picklist 公用方法的实现

    本篇参考:salesforce 零基础学习(六十二)获取sObject中类型为Picklist的field values(含record type) https://developer.salesfo ...

随机推荐

  1. 动态加载与插件系统的初步实现(3):WinForm示例

    动态加载与插件系统的初步实现(三):WinForm示例 代码文件在此Download,本文章围绕前文所述默认AppDomain.插件容器AppDomain两个域及IPlugin.PluginProvi ...

  2. 移动收入超PC端 盛大文学战略转型初见成效

    随着智能手机和平板电脑的普及,越来越多的互联网服务也开始向移动端拓展,除了传统的互联网服务如搜索.即时通信之外,网络文学这项新兴的互联网业务也没忽视对移动端的布局. 7月9日,中国最大的网络文学出版平 ...

  3. zoj 1610 Count the Colors(线段树延迟更新)

    所谓的懒操作模板题. 学好acm,英语很重要.做题的时候看不明白题目的意思,我还拉着队友一块儿帮忙分析题意.最后确定了是线段树延迟更新果题.我就欣欣然上手敲了出来. 然后是漫长的段错误.... 第一次 ...

  4. shell脚本作为保证PHP脚本不挂掉的守护进程实例

    前几天开始跑一份数据名单,名单需要提供用户名.是否有手机号.是否有邮箱,用户名单我轻易的获取到了,但是,用户名单有2000w之多,并且去检测用户是否有手机号.是否有邮箱必须得通过一个对外开放的安全接口 ...

  5. 【未来畅想】未来的电信通讯行业,账号密码将取代sim卡

    今天看到一条新闻,是关于LG模块化的手机,LG将手机电池模块化了,很多人一片叫好,但是我认为模块化手机无法成为未来的趋势,原因如下:模块化必然要增加手机的卡口.插口增,意味着体积也大大增加,手机正因为 ...

  6. 用php 进行对文件的操作 (上)

    如何让自己磁盘中的文件夹和目录显示在网页上?那就来看一下,用php是怎么来操作他们的吧 php中文件,一般包含两块内容,文件和目录 先来一句一句的看代码,及他的作用 运行后看一下结果 file 指的是 ...

  7. python中函数与函数之间的调用,总是晕菜,整理如下,有不对或者补充的请提出来~

    1.python函数基础 函数名: fun 函数体:1~3行 返回值:2 调用函数:fun() ,只有见到这个括号(),程序会根据函数名从内存中找到函数体,然后执行它. 2.函数的执行顺序 下面的fu ...

  8. 试图解释下ERP

    ERP,字面的意思就是企业资源规划.但现在基本上是企业信息系统的统称,过去叫MIS.我们就是有这个本事,不管什么高大上的事物,很快就会做的很烂. 你可以这样理解ERP. 现在来了个订单,你需要回答下面 ...

  9. 启动web项目,报内存不足错误的解决方法

    Initialization of bean failed; nested exception is java.lang.OutOfMemoryError: Java heap space 原因: 在 ...

  10. gridcontrol如何根据值来动态设置某一行的颜色

    应用场景:当我们使用devexpress gridcontrol wpf控件时.可要会要根据这一行要显示的值来设置相应的颜色 可以通过下面方法来实现 一.先定义一个style <local:Co ...