javascript 私有方法的实现

原文地址:

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.

时间: 2024-08-29 06:04:23

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

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

基于原生JS的jsonp方法的实现 jsonp,相信大家并不陌生,是在js异步请求中解决跨域的方法之一,原理很简单,有不清楚的同学可以google下,这里就补详细解释了.在Jquery库中,jQuery直接封装有jsonp的方法,很简便,只需在ajax请求的参数中加入datatype:jsonp,jsonp:jsonpcallback即可,这里写下用原生js实现jsonp的源码. load= function (url, cfg, success) { var op = Object.proto

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

首先来看一下String中hashCode方法的实现源码. public int hashCode() { int h = hash; if (h == 0 && value.length > 0) { char val[] = value; for (int i = 0; i < value.length; i++) { h = 31 * h + val[i]; } hash = h; } return h; } 在String中有一个私有实例字段hash表示该串的哈希值,在

JavaScript 私有成员

Class field declarations for JavaScript(JavaScript 类的字段声明)目前已经进入了 stage-3,其中包含一项 OOP 开发者都很关注的内容:Private fields.JavaScript 一直没有私有成员并不是没有原因,所以这一提议给 JavaScript 带来了新的挑战.但同时,JavaScript 在 ES2015 发布的时候已经在考虑私有化的问题了,所以要实现私有成员也并非毫无基础. 笔者在专栏<JavaScript 全栈工程师养成记

android客户端向服务器端验证登陆方法的实现1

遇到的问题:一个条件查询与多个条件查询,所用到的方式不一样 参考文档: http://www.oschina.net/question/1160609_133366    mybatis多条件查询的一个错误 解决方案如下: 利用序列号的方式解决多个参数的查询问题.对象与数据库关系的映射层. 层次结构如下: 首先定义model层里面的Userlist类,这是和我们后台mysql里面的表是一一对应的,然后定义UserlistMapper类,这个类主要是用来封装一些个方法,比如说增删改查等.其实现通过

matchesSelector及低版本IE中对该方法的实现

matchesSelector用来匹配dom元素是否匹配某css selector.它为一些高级方法的实现提供了基础支持,比如事件代理,parent, closest等. W3C在2006年就提出了该方法草案,Firefox和Safari相继实现,比如 ? 1 2 3 4 5 6 <div id="wraper" class="item"></div> <script>     wraper.mozMatchesSelector(

android客户端向服务器端验证登陆方法的实现2

一.在上一篇文章中,我只是提到了其中一种方法来实现登陆 大家可以参见: http://www.apkbus.com/android-45004-1-1.html      android获取web服务器端session并验证登陆 http://blog.csdn.net/cainiao123hack/article/details/8255848   服务器端向Android客户端传值--登录实现 http://zhidao.baidu.com/link?url=8g9EWhyUkUgUr1dh

深入分析Object.finalize方法的实现原理

“物有本末,事有始终.知其先后,则近道矣” finalize 如果类中重写了finalize方法,当该类对象被回收时,finalize方法有可能会被触发,下面通过一个例子说明finalize方法对垃圾回收有什么影响. public class FinalizeCase { private static Block holder = null; public static void main(String[] args) throws Exception { holder = new Block(

jQuery 中 data 方法的实现原理

前言:jQuery 作为前端使用最多最广泛的 JS 库,其源码每个 JSer 都应该研究一下.早就打算看却一直被各种事拖着,上次某公司面试时被问到 jQuery 中 data 方法是如何实现的,结果答不上来懊悔不已.现在终于下决心开始看 jQuery 的源码,就从 data 方法开始.本人也是前端新手,如果文章中有理解不当或者错误之处,欢迎留言指出,3Q~ jQuery 版本为 1.8.2 data() 的使用方法 // 向一个 dom 元素绑定数据 $("#header").data

Java String类中CaseInsensitiveComparator.compare()方法的实现

String对象的大小写不敏感比较方法的实现如下: 1 public int compare(String s1, String s2) { 2 int n1 = s1.length(); 3 int n2 = s2.length(); 4 int min = Math.min(n1, n2); 5 for (int i = 0; i < min; i++) { 6 char c1 = s1.charAt(i); 7 char c2 = s2.charAt(i); 8 if (c1 != c2)