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.
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 ...
随机推荐
- .net基础收集
.net基础收集 最近的面试让我知道基础知识的重要性,而我也每天都在网上找一些基础题来看.其实面试无非都是一些理论基础,只有基础过关了,才会被问到技术性的问题,所以第一关一定要打好.下面是我收集的一些 ...
- Reeder Web版
Reeder Web版 访Reeder界面效果 一直很欣赏触控手势的代码实现,所以最近折腾了个Javascript触控手势库--JTouch,效果还有诸多不完善之处,苦于硬件设备不完善,针对ie10的 ...
- OpenRisc-37-OpenRISC的CPU&core的整体架构分析
引言 前面我们分析了ORPSoC的整体架构,并对其子系统进行了深入的分析和了解.但对于ORPSoC的核心模块or1200_top及其内部的core--or1200_cpu模块却鲜有涉及,算是ORPSo ...
- Linux IO控制命令生成
在驱动程序里, ioctl() 函数上传送的变量 cmd 是应用程序用于区别设备驱动程序请求处理内容的值.cmd除了可区别数字外,还包含有助于处理的几种相应信息. cmd的大小为 32位,共分 4 个 ...
- java参数传递(值传递还是引用传递)
Java中的参数传递机制一直以来大家都争论不休,究竟是“传值”还是“传址(传引用)”,争论的双方各执一词,互不相让.不但“菜鸟”们一头雾水,一些“老鸟”也只知道结果却说不出所以然来.我相信看过下面的内 ...
- 对 Select 的各种操作(JQuery)
在写表单时,经常要用到select元素,这个元素相较于其他文本框标签而言有不同.最近在写一个页面表单时需要对select进行各种操作,现将其用法收集并总结如下: HTML元素: <select ...
- C语言之全局变量和局部变量
全局变量和局部变量的简介(tips:很重要 牢记) 全局变量:就是定义在函数外的变量 全局变量可以在任意函数中使用 生命周期:程序一启动就开辟空间,直到程序退出才回收 全局变量不允许同名 局部变量:就 ...
- [ios2] CABasicAnimation【转】
caanimation 整理了解 http://geeklu.com/2012/09/animation-in-ios/ 几个可以用来实现热门APP应用PATH中menu效果的几个方法 +(CABa ...
- jmeter压力测试的简单实例+badboy脚本录制(一个简单的网页用户登录测试的结果)
JMeter的安装:在网上下载,在下载后的zip解压后,在bin目录下找到JMeter.bat文件,双击就可以运行JMeter. http://jmeter.apache.org/ 在使用jmeter ...
- php 语言特点
PS:绝大多数用php的企业/ 项目 活不到雇佣得起月薪35k以上的php程序员那一天,也是php码农在10年经验的时候普遍不如java程序员的原因之一. PS2: 由于薪资提升太快,很多php码农跳 ...