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 closure02.(function(){03. 04.//this is a private static member that is only available in this closure05.var instances = 0;06. 07.//this is a private static method that can be used internally08.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 SomeClass15.if (!(this instanceOf SomeClass))16.return new SomeClass(options);17. 18.//call static method19._doSomething();20. 21.//handle the options initialization here22.}23. 24.//create a public static method for SomeClass25.this.SomeClass.getInstanceCount = function() {26.return instances; //returns the private static member value27.}28. 29.//create an instance method for SomeClass30.this.SomeClass.prototype.doSomething = function() {31./*Do Something Here*/32.}33. 34.//end private closure then run the closure, localized to My.Namespace35.}).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 instance02.var sc = new My.Namespace.SomeClass({/* options go here */});03. 04.//call SomeClass as a function, which will return an instance05.// defined above via "(!(this instanceOf SomeClass))"06.var sc = My.Namespace.SomeClass({/* options */});07. 08.//view the instance count, which uses a public static method09.// 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.NameSpace03.var m = My.NameSpace04. 05.//bad form assigning onload internally,06.// but that'll be for another post on event binding07.// 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 私有方法的实现的更多相关文章
- JavaScript 类私有方法的实现
一:将私有方法移出模块,因为模块内部的所有方法都是对外可见的. class Widget { foo (baz) { bar.call(this, baz); } // ... } function ...
- JavaScript中子类调用父类方法的实现
一.前言 最近在项目中,前端框架使用JavaScript面向对象编程,遇到了诸多问题,其中最典型的问题就是子类调用父类(super class)同名方法,也就是如C#中子类中调用父类函数base.** ...
- JavaScript内置一些方法的实现原理--new关键字,call/apply/bind方法--实现
先学习下new操作符吧 new关键字调用函数的心路历程: 1.创建一个新对象 2.将函数的作用域赋给新对象(this就指向这个对象) 3.执行函数中的代码 4.返回这个对象 根据这个的思路,来实现一个 ...
- Atitit paip.对象方法的实现原理与本质.txt
Atitit paip.对象方法的实现原理与本质.txt 对象方法是如何实现的1 数组,对象,字典1 对象方法是如何实现的 这显然是一个对象方法调用.但对象方法是如何实现的呢?在静态语言中,因为有编译 ...
- OC:属性的内部实现原理、dealloc内释放实例变量、便利构造器方法的实现原理、collection的内存管理
代码: // // main.m #import <Foundation/Foundation.h> #import "Person.h" #import " ...
- 基于原生JS的jsonp方法的实现
基于原生JS的jsonp方法的实现 jsonp,相信大家并不陌生,是在js异步请求中解决跨域的方法之一,原理很简单,有不清楚的同学可以google下,这里就补详细解释了.在Jquery库中,jQuer ...
- 关于Java中hashCode方法的实现源码
首先来看一下String中hashCode方法的实现源码. public int hashCode() { int h = hash; if (h == 0 && value.leng ...
- js中的bind方法的实现方法
js中目前我遇见的改变作用域的5中方法:call, apply, eval, with, bind. var obj = { color: 'green' } function demo () { c ...
- Salesforce LWC学习(十五) Async 以及 Picklist 公用方法的实现
本篇参考:salesforce 零基础学习(六十二)获取sObject中类型为Picklist的field values(含record type) https://developer.salesfo ...
随机推荐
- 纯Python综合图像处理小工具(3)10种滤镜算法
<背景> 滤镜处理是图像处理中一种非常常见的方法.比如photoshop中的滤镜效果,除了自带的滤镜,还扩展了很多第三方的滤镜效果插件,可以对图像做丰富多样的变换:很多手机app实现了实 ...
- python email ==> send 发送邮件 :) [smtplib, email 模块]
关于Email的预备知识: 原贴地址:http://www.cnblogs.com/lonelycatcher/archive/2012/02/09/2343480.html ############ ...
- KL25的AD采集操作
飞思卡尔的KL25单片机AD做的是很不错的,SAR型能做到16位.不过数据手册就写得不怎么样了,简直可以说是坑爹,很难看懂.有的描述让人难以理解,你指望在别的地方对不理解的地方会有其他角度的描述,结果 ...
- Java项目中打开本地文件的方法
1:其中saveAddress 为已知本地文件全路径: Desktop.getDesktop().open(new File(saveAddress));
- redis 学习笔记——redis集群
redis-cluster 简介 redis-cluster是一个分布式.容错的redis实现,redis-cluster通过将各个单独的redis实例通过特定的协议连接到一起实现了分布式.集群化的目 ...
- SmoOne——开源免费的企业移动OA应用,基于VS.Net
一.SmoOne是什么一个开源的移动OA应用 二.语言.Net 三.开发环境Visual Studio 四.开发平台Smobiler Designer 五.功能该应用开源代码中包含注册.登录.用户信息 ...
- LeetCode题解 15题 第二篇
之前写过一篇,这是第二篇.上一篇用了多种编程语言来做,这一次是以学算法为主,所以打算都用python来完成. 4. Median of Two Sorted Arrays There are two ...
- luogu P2580 于是他错误的点名开始了
luogu P2580 于是他错误的点名开始了 https://www.luogu.org/problem/show?pid=2580 题目背景 XS中学化学竞赛组教练是一个酷爱炉石的人. 他会一边 ...
- C++ STD inner_product函数
C++ STD函数 inner_product是c++标准库封装的一个函数. 函数原型: 函数1: inner_product(beg1, end1, beg2, init) 函数2: inner ...
- git stash让bug来的更猛烈些吧
git stash可以用来暂存当前正在进行的工作,比如想pull最新的代码,又不想加新commit, 或者有一个紧急的bug需要修复,但是这个bug又与你已经在做的工作(还没完成)有关联.这个时候有的 ...