从3.2.15 逐步升级到 5.0.0 真受痛苦,之后的版本由于本人愚钝。。。还是无法升级至最新的isroc。。。。
话说最新的编辑器让我非常郁闷。。。缺少了代码的所见即所得的部分。。。。
从3.2.15 逐步升级到 5.0.0 真受痛苦,之后的版本由于本人愚钝。。。还是无法升级至最新的isroc。。。。
话说最新的编辑器让我非常郁闷。。。缺少了代码的所见即所得的部分。。。。
本周最值得关注的blog:
http://blog.kaourantin.net/ 之 http://www.kaourantin.net/2010/03/timing-it-right.html 及 http://blog.kaourantin.net/?p=83
受影响的 API和类:
EI LC Timer EnterFrame throw 等
新的Trine计划有待测试
C# 代码
- using System;
- using System.Security.Cryptography;
- namespace YNIT.Components
- {
- /// <summary>
- /// 生成随机字符串的密封类,不能被继承
- /// </summary>
- public sealed class RandomStr
- {
- private static readonly int defaultLength = 8;
- private static int GetNewSeed()
- {
- byte[] rndBytes = new byte[4];
- RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider();
- rng.GetBytes(rndBytes);
- return BitConverter.ToInt32(rndBytes,0);
- }
- private static string BuildRndCodeAll(int strLen)
- {
- System.Random RandomObj = new System.Random(GetNewSeed());
- string buildRndCodeReturn = null;
- for(int i=0; i<strLen; i++)
- {
- buildRndCodeReturn += (char)RandomObj.Next(33,125);
- }
- return buildRndCodeReturn;
- }
- #region 输出随机字符串
- /// <summary>
- /// 输出长度为8的随机字符串
- /// </summary>
- /// <returns>长度为8的随机字符串</returns>
- public static string GetRndStrOfAll()
- {
- return BuildRndCodeAll(defaultLength);
- }
- /// <summary>
- /// 输出指定长度的随机字符串
- /// </summary>
- /// <param name="LenOf">长度</param>
- /// <returns>指定长度的随机字符串</returns>
- public static string GetRndStrOfAll(int LenOf)
- {
- return BuildRndCodeAll(LenOf);
- }
- #endregion
- private static string sCharLow = "abcdefghijklmnopqrstuvwxyz";
- private static string sCharUpp = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
- private static string sNumber = "0123456789";
- private static string BuildRndCodeOnly(string StrOf,int strLen)
- {
- System.Random RandomObj = new System.Random(GetNewSeed());
- string buildRndCodeReturn = null;
- for(int i=0; i<strLen; i++)
- {
- buildRndCodeReturn += StrOf.Substring(RandomObj.Next(0,StrOf.Length-1),1);
- }
- return buildRndCodeReturn;
- }
- #region 输出指定范围随机字符串
- /// <summary>
- /// 输出长度为8的小写字母加数字的字符串
- /// </summary>
- /// <returns>长度为8的小写字母加数字的字符串</returns>
- public static string GetRndStrOnlyFor()
- {
- return BuildRndCodeOnly(sCharLow + sNumber,defaultLength);
- }
- /// <summary>
- /// 输出指定长度的小写字母加数字的字符串
- /// </summary>
- /// <param name="LenOf">长度</param>
- /// <returns>指定长度的小写字母加数字的字符串</returns>
- public static string GetRndStrOnlyFor(int LenOf)
- {
- return BuildRndCodeOnly(sCharLow + sNumber,LenOf);
- }
- /// <summary>
- /// 输出长度为8的指定字符串
- /// </summary>
- /// <param name="bUseUpper">是否含有大写字母</param>
- /// <param name="bUseNumber">是否含有数字</param>
- /// <returns>长度为8的指定字符串</returns>
- public static string GetRndStrOnlyFor(bool bUseUpper,bool bUseNumber)
- {
- string strTmp = sCharLow;
- if (bUseUpper) strTmp += sCharUpp;
- if (bUseNumber) strTmp += sNumber;
- return BuildRndCodeOnly(strTmp,defaultLength);
- }
- /// <summary>
- /// 输出指定长度的指定字符串
- /// </summary>
- /// <param name="LenOf">长度</param>
- /// <param name="bUseUpper">是否含有大写字母</param>
- /// <param name="bUseNumber">是否含有数字</param>
- /// <returns>指定长度的指定字符串</returns>
- public static string GetRndStrOnlyFor(int LenOf,bool bUseUpper,bool bUseNumber)
- {
- string strTmp = sCharLow;
- if (bUseUpper) strTmp += sCharUpp;
- if (bUseNumber) strTmp += sNumber;
- return BuildRndCodeOnly(strTmp,LenOf);
- }
- #endregion
- }
按:看到如此细致的文章,真的很爱~~ 转载如此。向作者致敬~!
很久以前Roger Johansson就在他的blog上做了一个用样式控制表单元素的测试, 告诉我们企图用样式控制表单元素是一件不可能的事情
using CSS to style form controls to look exactly the same across browsers and platforms is impossible
甚至css2.1规范中也没有明确这方面的规定, 而是打算将它fix in future
CSS 2.1 does not define which properties apply to form controls and frames, or how CSS can be used to style them. User agents may apply CSS properties to these elements. Authors are recommended to treat such support as experimental. A future level of CSS may specify this further.
所以如果想要让表单元素在各个浏览器下完全一致, 最好的解决方法莫过于完全不理会操作系统的样式, 用自定义的ui风格, 就像bing或Google的Jazz UI那样

然而, 这会导致界面和用户的系统格格不入, 目前google主要还是针对浏览器做了些特殊处理, 如webkit下用gradient使得按钮看上去好些

mac下webkit的按钮不好控制

本文将就输入框高度的问题进行调研, 寻找更好的解决方法
首先, 这个调研的一个主要原因是, 搜索结果页打算进入标准模式, 这会导致盒模型的变化, 造成输入框高度和原来不一样, 所以为了和线上效果保持一致, 我们需要找到一个最佳的解决方案
有同学可能会不解, 有那么难么? 设置一个height不就解决了么?
<input type="text" style="height:28px" />
然而, 经测试发现这里面的细节问题还是还挺多, 由于资源有限, 这里只测试了主要的浏览器和平台, 包括目前主要用到的5个浏览器
我们的目标是和目前搜索框大小保持一致, 既28px
首先测试的是最简单的height, 先看目前线上的方案(简单起见就直接写到style中了)
<input type="text" style="font: 16px arial; height: 1.78em; padding-top:2px" />
从样式上推导, 由于盒模型问题, 在IE下的大小将是1.78 * 16 = 28px, 而Firefox等浏览器应该是1.78 * 16 + 2px + border-width * 2 = 30 + ? px
测试结果是
| 浏览器 | height + padding-top + padding-bottom + border-top-width + border-bottom-width |
|---|---|
| IE6(xp) | 21 + 2 + 1 + 2 + 2 = 28 |
| IE7(xp) | 21 + 2 + 1 + 2 + 2 = 28 |
| IE8(win7) | 21 + 2 + 1 + 2 + 2 = 28 |
| Firefox 3.5(xp) | 21 + 2 + 1 + 2 + 2 = 28 |
| Firefox 3.5(win7) | 23 + 2 + 1 + 1 + 1 = 28 |
| Firefox 3.5(mac 10.6.2) | 19 + 2 + 1 + 3 + 3 = 28 |
| Firefox 3.5(ubuntu 10.04) | 19 + 2 + 1 + 3 + 3 = 28 |
| Chrome 5(xp) | 21 + 2 + 1 + 2 + 2 = 28 |
| Chrome 5(win7) | 21 + 2 + 1 + 2 + 2 = 28 |
| Chrome 5(mac 10.6.2) | 21 + 2 + 1 + 2 + 2 = 28 |
| Chrome 5(ubuntu 10.04) | 21 + 2 + 1 + 2 + 2 = 28 |
效果相当理想, 所有浏览器都是28px, 看来即使是Firefox和Chrom在quirks模式下的input都没有遵循盒模型, 所以线上的输入框高度在各个浏览器下很完美地保持一致
然而如果是在standards模式下, 结果则是
| 浏览器 | height + padding-top + padding-bottom + border-top-width + border-bottom-width |
|---|---|
| IE6(xp) | 28 + 2 + 1 + 2 + 2 = 35 |
| IE7(xp) | 28 + 2 + 1 + 2 + 2 = 35 |
| IE8(win7) | 28 + 2 + 1 + 2 + 2 = 35 |
| Firefox 3.5(xp) | 28 + 2 + 1 + 2 + 2 = 35 |
| Firefox 3.5(win7) | 28 + 2 + 1 + 1 + 1 = 32 |
| Firefox 3.5(mac 10.6.2) | 28 + 2 + 1 + 3 + 3 = 37 |
| Firefox 3.5(ubuntu 10.04) | 28 + 2 + 1 + 3 + 3 = 37 |
| Chrome 5(xp) | 28 + 2 + 1 + 2 + 2 = 35 |
| Chrome 5(win7) | 28 + 2 + 1 + 2 + 2 = 35 |
| Chrome 5(mac 10.6.2) | 28 + 2 + 1 + 2 + 2 = 35 |
| Chrome 5(ubuntu 10.04) | 28 + 2 + 1 + 2 + 2 = 35 |
就仅仅加了一句
, 却导致浏览器差距变得如此大, 仔细观察发现, 主要问题在Firefox上 它的border在win7下是1像素, xp下是2像素, mac下是3像素, 令人很头疼, 于是打算换一种方案试试
由于Firefox的border问题, 设定height是不可能保证高度一致的, 除非判断再去判断操作系统类型, 但那样做太麻烦了, 而且说不定mobile版又不一样
那是否可以不通过设置height来控制? 在目前的大搜索首页也是standards模式, 它是采用padding的方式来实现28px的高度的
<input type="text" style="font: 16px arial; padding:3px" />
这种写法的测试结果是
| 浏览器 | height + padding-top + padding-bottom + border-top-width + border-bottom-width |
|---|---|
| IE6(xp) | 18 + 3 + 3 + 2 + 2 = 28 |
| IE7(xp) | 18 + 3 + 3 + 2 + 2 = 28 |
| IE8(win7) | 18 + 3 + 3 + 2 + 2 = 28 |
| Firefox 3.5(xp) | 19 + 3 + 3 + 2 + 2 = 29 |
| Firefox 3.5(win7) | 19 + 3 + 3 + 1 + 1 = 27 |
| Firefox 3.5(mac 10.6.2) | 20 + 3 + 3 + 3 + 3 = 32 |
| Firefox 3.5(ubuntu 10.04) | 19 + 3 + 3 + 3 + 3 = 31 |
| Chrome 5(xp) | 19 + 3 + 3 + 2 + 2 = 29 |
| Chrome 5(win7) | 19 + 3 + 3 + 2 + 2 = 29 |
| Chrome 5(mac 10.6.2) | 18 + 3 + 3 + 2 + 2 = 28 |
| Chrome 5(ubuntu 10.04) | 19 + 3 + 3 + 2 + 2 = 29 |
在不设定输入框高度的情况下, 浏览器会自行指定一个, 而且都有差距, mac上的Firefox更是高出了4像素, 但总的来说, 效果虽然不完美, 但还是可以接受, 大部分情况下都只差一个像素
然而这种方法带来了很多不确定性, 内容区的高度是随着字体大小而变的, 假设font-size是14px, 浏览器的高度又保持一致了
| 浏览器 | height |
|---|---|
| IE6(xp) | 16 |
| IE7(xp) | 16 |
| IE8(win7) | 16 |
| Firefox 3.5(xp) | 16 |
| Firefox 3.5(win7) | 16 |
| Firefox 3.5(mac 10.6.2) | 16 |
| Firefox 3.5(ubuntu 10.04) | 16 |
| Chrome 5(xp) | 16 |
| Chrome 5(win7) | 16 |
| Chrome 5(mac 10.6.2) | 16 |
| Chrome 5(ubuntu 10.04) | 16 |
是否还有更好的方案呢?
height和padding都无法完美控制输入框高度, 而border的大小又不能改, 难道就真的没办法了么? 不禁怀念quirks模式下的方便, 设定一个高度就完美了, 要是能既进standards模式, 又能用到旧盒模型就好了, 很自然地就想到了一个从来没用过的css属性box-sizing, 以前一直没想好这属性到底能用在哪里, 终于这下派上用场了, 使用它我们就可以解决Firefox下3种border的区别, 让Firefox自己去算内容区的高度
然而由于IE6/7不支持这个属性, 所以需要写hack, 由于IE下的默认border值是2, padding是1, 所以height需要减6像素, 也就是
-moz-box-sizing: border-box;
-webkit-box-sizing: border-box;
box-sizing: border-box;
height: 28px;
*height: 22px;
这样, 就能保证绝大部分的浏览器下效果一致了, box-sizing属性的支持情况如下表所示, 来自mozilla, 支持的访问非常广
| Browser | Lowest Version | Support of |
|---|---|---|
| Internet Explorer | 8.0 | box-sizing |
| Firefox (Gecko) | 1.0 (1.0) | -moz-box-sizing |
| Opera | 7.0 | box-sizing |
| Safari (WebKit) | 3.0 (522) | -webkit-box-sizing |
不过, 事情还没有结束, 刚才假定了IE下默认padding是1像素, 然而目前很多css reset都会将input的padding设为0, 于是, IE下的差别将不是6像素, 而是4像素, 所以为了避免受到影响, 建议将padding设为0
padding-top: 0;
padding-bottom: 0;
height: 28px;
*height: 24px;
回过头来看Firefox和Chrome在quirks模式下使用了非标准的盒模型, 看样子是有意去做的, 它是如何实现的呢?
于是在webkit源码中寻找, 一开始以为它是在源码中对quirks下的input做了特殊处理, 但没看找到又什么特别的地方, 而在看到计算box高度的时候
int RenderBox::calcContentBoxHeight(int height) const
{
if (style()->boxSizing() == BORDER_BOX)
height -= (borderTop() + borderBottom() + paddingTop() + paddingBottom());
return max(0, height);
}
忽然想到, 会不会是通过浏览器默认样式来实现的呢? 将这种特殊的逻辑直接写在代码中确实太恶心了, 既然支持box-sizing属性, 直接将它写在quirks的默认样式不就完美解决了么
果然, 在Firefox的res/quirk.css中发现了这句
/*
* Quirk: Use border-box box sizing for text inputs, password inputs, and
* textareas. (b=184478 on why we use content-box sizing in standards mode)
*/
/* Note that all other
<input>s already use border-box
sizing, so we're ok with this selector */
input:not([type=image]), textarea {
-moz-box-sizing: border-box;
}
在webkit源码中的WebCore/css/quirks.css发现了这句
/* This will apply only to text fields, since all other inputs already use border box sizing */
input:not([type=image]), textarea {
-webkit-box-sizing: border-box;
}
原来浏览器就是这么解决的, 那么在标准模式下用它将是一种比较好的方案
不过这种写法在Firefox 3.5以下的版本会有个问题, 那就是输入框内容将无法垂直居中, 以英文为例, 3.5中和顶部的差距是5像素, 而3.6是7像素, 目前还没想到解决方案

幸好在Firefox 3.6中解决了这个问题, 而且3.5会默认升级到3.6, 所以这个问题也就不需要考虑了
从这个例子可以痛苦地体验, 如果没有统一的规范, 要兼容不同浏览器是如此的困难, 而且这还仅仅是一个很不完全的测试, 好在浏览器还是尽可能做到了最大兼容, 比如, 假设windows下默认主题和经典主题有区别, 就意味着所有windows下的测试都要乘2
Mercurial 是一个轻量级的分布式版本控制系统,它以方便的控制、极强的扩展性赢得了众多开放源代码项目的青睐。本文从版本控制系统中的基本概念、操作和扩展性等方面,有侧重的介绍了 Mercurial。此外本文列出了几个其他常用的分布式版本控制系统,并和 Mercurial 作了简单的比较。通过阅读本文,读者可以了解基础的Mercurial操作,进而熟悉这个备受青睐的工具。
changeset: 207:58e4906e69e3 |
$ hg command [options]
|
$ hg help command
|
$ hg clone http://foo.com/hg/project1
|
destination directory: project1
requesting all changes
adding changesets
adding manifests
adding file changes
added 127 changesets with 448 changes to 143 files
139 files updated, 0 files merged, 0 files removed, 0 files unresolved
|
$ hg init |
def main():
print "I'm in the a function."
print "Great joy of using Mercurial!" #新加的一行
if __name__ == "__main__":
sys.exit(main())
|
$ hg status M main.py |
diff -r a58db6f0e482 main.py
--- a/main.py Thu Nov 29 13:38:38 2007 +0800
+++ b/main.py Thu Nov 29 13:46:10 2007 +0800
@@ -1,5 +1,6 @@ def main():
def main():
print "I'm in the a function."
+ print "Great joy of using Mercurial!" #新加的一行
if __name__ == "__main__":
sys.exit(main())
|
$ hg commit |
HG: user: Guolian Yun <yunguol@cn.ibm.com> HG: changed main.py |
I’m using Mercurial! HG: user: Guolian Yun <yunguol@cn.ibm.com> HG: changed main.py |
$ hg status |
$ hg tip: changeset: 2:2874393e3d9c tag: tip user: Guolian Yun <yunguol@cn.ibm.com> date: Thu Nov 29 10:10:39 2007 +0800 summary: I'm using Mercurial! |
$ hg push project2 |
$ hg pull project3 |
$ hg pull -u |
file://local/filesystem/path http://[user@]host[:port]/[path] https://[user@]host[:port]/[path] ssh://[user@]host[:port]/[path] |
hg 后被调用时就像原生的命令一样。本文介绍两个常用的Mercurial扩展:Patchbomb和Mq。email命令。通过调用 hg email 命令,changeset 提交时的信息的第一行将作为邮件的主题,信件的正文包括完整的 changese t提交信息,以 patch 的形式发布出来的 changeset 完整补丁。如果一次发送的是多个changeset,那么Patchbomb会提示输入本次 changeset 集的总提示信息,这部分信息将作为第一封信,信件主题以[PATCH 0 of N]开头,changeset 则会以[PATCH i of N]将的主题开头发出,其中i是 changeset在本地 repository 当中的顺序。多changeset 系列邮件中,每封信会在邮件头中包含合适的回复信息,这样在邮件客户端可以清晰的显示出系列 changeset 之间的层次关系。.hgrc 当中设置,以下是一个完整的例子。
[extensions] hgext.patchbomb = [email] method = smtp # 还可以在这里指定/usr/sbin/sendmail from = Zhengang Li <lizg@cn.ibm.com> to = groupmail@foo.com [smtp] host = smtp.foo.com |
.hgrc 当中添加如下信息:
[extensions] hgext.mq= |
qinit, qnew, qrefresh, qdiff, qpop和qpush等。Qinit 用来初始化用来存放补丁队列的目录,qnew创建一个新的补丁changeset,qrefresh 将改动刷新到当前的补丁当中去,qdiff 将当前的补丁打印到屏幕,qpop 和 qpush 用来移动当前存放在队列顶部的补丁。完整的 q 系列命令可以从 hg help给出的列表中获得。.hg/patches下面,用户可以手动修改这些补丁当中的提交信息。Changeset 补丁的顺序存放在.hg/patches/series文件当中,同样的,用户可以修改这些补丁的顺序。
本文主要实现了一个轻量的JavaScript OOP框架,并借此讨论了基于运行时覆写实现基类方法调用的技术以及实现保护成员的方法。
A lightweight JavaScript OOP framework was implemented in this text. Base-method invocation implementation technique, using runtime overwriting, and implementation of protected members was discussed here.
我终于这个优雅且几乎完美的JavaScript OOP 实现——轻便,简洁,并且有效。(暂且命名为emop)
Finally I've found the elegant implementation of almost-perfect OOP framework implementation in Javascript. It's light, clear, and, effective.(temporarily named emop)
- var Class;
- void function() {
- var mgBaseGen = function(bcl, original) {
- return function(nname) {
- var c = bcl, rv;
- while (c && !c.prototype.hasOwnProperty(nname)) c = c.baseConstructor;
- if (!c) throw new Error('Cannot find base class with specific methods');
- this.base = mgBaseGen(c.baseConstructor, this.base);
- try {
- rv = c.prototype[nname].apply(this, Array.prototype.slice.call(arguments, 1));
- } finally {
- this.base = original;
- };
- return rv;
- };
- };
- // Token
- var CHECK = {};
- // Empty function
- var NULLFUNC = function() {};
- // hasOwnProperty checker
- var HOPCHECKER = {};
- // protected properties name
- var protectedName = '..protected..';
- var registerProtecteds = function(o) {
- var protecteds = [];
- var p = function(checker, name, value) {
- if (checker !== CHECK) throw new Error('access denied');
- if (arguments.length > 2) return protecteds[name] = value;
- else if (HOPCHECKER.hasOwnProperty.call(protecteds, name)) return protecteds[name];
- };
- p.length = 0;
- p.toString = function() {
- throw new Error('access denied')
- };
- o[protectedName] = p;
- };
- var bound = null;
- var priv = function(n, v) {
- if (!HOPCHECKER.hasOwnProperty.call(bound, protectedName)) {
- if (protectedName in bound) {
- registerProtecteds(bound);
- } else {
- return new Error('access denied');
- }
- }
- if (arguments.length > 1) return bound[protectedName](CHECK, n, v);
- else return bound[protectedName](CHECK, n);
- };
- var wrapProtected = function(method) {
- return function() {
- var hold = bound;
- bound = this;
- try {
- var ret = method.apply(this, arguments);
- } finally {
- bound = hold;
- return ret;
- }
- }
- }
- // catalogs
- var NClassBase = null;
- var NAttachments = [];
- Class = function(Definition, proto) {
- // stack backup
- var BClassBase = NClassBase;
- var BAttachments = NAttachments;
- // clear attachments array
- NAttachments = [];
- try {
- // constructor
- var ctor, def = new Definition(priv);
- if (def.initalize instanceof Function) {
- ctor = wrapProtected(def.initalize);
- } else {
- ctor = NULLFUNC;
- };
- delete def.initalize;
- // create class
- var Clz = function() {
- registerProtecteds(this);
- return ctor.apply(this, arguments);
- };
- //bind prototype
- if (proto instanceof Function || NClassBase instanceof Function) {
- if (proto instanceof Function) {
- Clz.prototype = new proto;
- Clz.baseConstructor = proto;
- } else if (NClassBase instanceof Function) {
- Clz.prototype = new NClassBase;
- Clz.baseConstructor = NClassBase;
- };
- Clz.prototype.base = function(name) {
- var c = Clz.baseConstructor, rv, cler = arguments.callee.caller.caller;
- var original = this.base;
- this.base = mgBaseGen(c, original);
- try {
- rv = this.base.apply(this, arguments);
- } finally {
- this.base = original;
- };
- return rv;
- };
- } else {
- if (proto) Clz.prototype = proto;
- else Clz.prototype = {};
- Clz.baseConstructor = Object; // need to be fixed;
- };
- proto = Clz.prototype;
- //attachments
- for (var i = 0; i < NAttachments.length; i++) {
- var item = NAttachments[i][0];
- var args = [proto].concat(NAttachments[i][1]);
- item.apply(proto, args);
- }
- //reflect methods
- for (var each in def) if (def.hasOwnProperty(each)) {
- if (def[each] instanceof Function) {
- var f = wrapProtected(def[each]);
- f.toString = function() {
- return def[each].toString()
- };
- f.length = def[each].length;
- proto[each] = f;
- } else {
- proto[each] = def[each];
- }
- };
- } finally {
- NClassBase = BClassBase;
- NAttachments = BAttachments;
- return Clz;
- };
- };
- Class.base = function(f) {
- NClassBase = f;
- };
- Class.attach = function(attachment, _args_) {
- NAttachments.push([attachment, Array.prototype.slice.call(arguments, 1)]);
- };
- Function.prototype.derive = function(definition) {
- return Class(definition, this);
- };
- Function.prototype.asClass = function(base) {
- return Class(this, base);
- }
- }();
- //Usage
- var Greeter = function() {
- this.greet = function() {
- alert('hello!');
- }
- }
- var A = function(priv) {
- Class.attach(Greeter);
- this.f = function(t) {
- priv('y', t);
- alert(priv('y'));
- };
- }.asClass();
- var B = A.derive( function(priv) {
- var Point = function(p) {
- this.initalize = function(x, y) {
- p('x', x);
- p('y', y);
- };
- this.abs = function() {
- var x = p('x');
- var y = p('y');
- return Math.sqrt(x * x + y * y);
- };
- }.asClass();
- this.g = function(p, q) {
- alert((new Point(p, q)).abs());
- };
- this.f = function(t) {
- this.base('f', t);
- alert('-- ' + t);
- }
- this.inter = function(obj, t) {
- obj.f(t)
- };
- });
- var foo = new B();
- foo.greet();
- foo.f(2);
- var foo2 = new B();
- foo2.g(5, 5);
- foo2.inter(foo, 3);
长期以来JavaScript程序员感到JavaScript的诸多掣肘之一就是它没有“完整的”OOP支持。尽管JavaScript利用原型系 统提供了OOP功能,但它没有提供这些特性:保护成员和基类方法调用。这段代码就是为了解决此问题。
For a long time, one of its limits which JavaScript programmers found is that it cannot provide "complete" OOP support. Although OOP was provided by the prototype system, the following charactics are absent: protected members and base method invocation. The target of this code is to solve this problem.
定义类的是一个函数,和传统的JavaScript构造器类似:
What defines a class is a function, written in thetraditional way:
- function(priv) {
- this.g = function(t) {
- priv('x', t);
- alert(priv('x'));
- };
- this.f = function(t) {
- this.base('f', t);
- alert('-- ' + t);
- }
- }
你可以看见类似传统“构造器”的东西——用this.methodName定义方法。不过,这里有一个很奇怪的priv参 数——它就是保护乘员的读写器。类定义将会传入Class函数,经过一系列复杂的转化后,返回我们需要的构造器。获得这个类只 要通过下面一句:
You can see something like traditional JavaScript constructors--defineing methods via "this.methodName". But, a strange method named "priv" appears here.It's the accessor of protected members. Such class definition will be sent into Class, and after a series of complicated transformation, the constructor we need yields.Getting this class can even use only one statement:
- A = Class(definition, base)
第一个参数是定义,第二个是其基类。
The first argument is the definition, the second is its base class.
emop还有两个语法糖:一个是Function.prototype.asClass,另一个是Function.prototype.derive。 它们分别定义为:
There are also 2 syntax sugars in emop: one is Function.prototype.asClass, the other is Function.prototype.derive. Their definitions are:
- Function.prototype.derive = function(definition) {
- return Class(definition, this);
- };
- Function.prototype.asClass = function(base) {
- return Class(this, base);
- }
你已经看到了,一个类定义很像一个构造器,但事实上不是。类定义是个函数,而且真的会运行,但只会运行一次。事实上构造器是由其定义的initalize方 法描述:
You have seen that a class definition looks like a constructor, but it in't. Class definition is a function, and it will be invoked, but only once. Actually, the exact constructor is described by initalize method which the definition defines:
- var Point = Class(function(p) {
- this.initalize = function(x, y) {
- p('x', x);
- p('y', y);
- };
- this.abs = function() {
- var x = p('x');
- var y = p('y');
- return Math.sqrt(x * x + y * y);
- };
- });
上面的Point是一个极好的例子。当我们要构造一个点的时候,虽然代码像下面的这样:
The Point above is a good example. When we need to construction a point, the following code appears:
- var p1 = new Point(0, 0);
你可能已经发现第一段代码中有几个很有趣的方法:
Maybe you've found some interesting methods in the first code paragraph:
Class.attach Class.base “priv” (instance).base 上面几个“特殊”方法的用途分别是:
Usages of the "special" methods are:
priv因为类定义是一个函数,它的第一个参数就是存取保护成员的读写器。在emop中一个对象拥有一般成员(和JavaScript中的一样)和保护成员 (只能用这个读写器访问)。因为方法定义总是包含在类定义中,所以priv可以被访问到,对象方法可以使用priv读 写保护成员:
Because class definition is a function, it's first paramater is the accessor of protected memners. Objects in emop contains normal members (like that in native JavaScript object) and protected members(only accessable by this accessor). Because the method definition is always contained by class definition, priv can be accessed and methods can use it to access protected members:
- this.m = function() {
- priv('x'); // get
- priv('x', 1); // set
- }
在这个例子中,m方法可以自由读写'x'保护成员。但priv在 类定义外就不能访问了,所以外界不能经过priv读写保护成员。
In this example, method m can access protected member 'x' freely. But priv is not accessable outside the class definiton, so outside program cannot access protected members via priv.
priv有两种调用方法:
There are two ways to invoke priv:
- priv('x'); // get
- priv('x', 1); // set
传入一个参数意味着读取,传入两个参数就是写入。
Passing one argument means reading, two means writing.
因为是保护成员,所以基类定义的方法和派生类定义的方法都可以使用priv访问。
Because it is protected members, base methods and derived methods can both access it via priv.
- var A = Class( function(p) {
- this.f = function() {
- p('x', 1)
- }
- });
- var B = Class( function(p) {
- this.g = function() {
- return p('x')
- }
- },A);
- var obj = new B();
- obj.f();
- obj.g(); // --> 1
Class.base and Class.attachemop规定一个类只有一个基类,Class.base就描述基类。而Class.attch则 描述了混入类。混入类定义类似类定义,但它是直接apply到某类的prototype上。显然, 混入类不能拿到保护成员读写器priv。上面的那段代码可以改写成:
emop declared that a class have only one base class, and it is defined by Class.base. Class.attach describes mixins. Mixin definition looks like class definition, but it is directly apply-ed to the prototype of some class. Obviously, mixins cannot get protected member acceessor "priv". Code above can be written like:
- var A = Class( function(p) {
- this.f = function() {
- p('x', 1)
- }
- });
- var B = Class( function(p) {
- Class.base(A);
- this.g = function() {
- return p('x')
- }
- });
- var obj = new B();
- obj.f();
- obj.g(); // 1
因此,定义派生类有两种方法:
So, derived class can be defined in two ways:
- Derived = Class( function() {......
- },Base)
- Derived = Class( function() {
- Class.base(Base);......
- })
下面的情况下,Base1是Derived的基类。另一个被抛弃:
Under the following situation, Base1 is the base class of Derived, Not Base2
- Derived = Class( function() {
- Class.base(Base2);......
- },Base1)
混入类可以参数化——当调用Class.attach(mixin,a,b,c)时,传入mixin的 第一个参数是被定义类的prototype,接着是a,b,c。传入的this指 针也是那个prototype:
Mixins can be parameterized -- When invoking Class.attach(mixin,a,b,c), First argument passed into mixin is the prototype of defined class, following arguments are a,b and c. this pointer passed is also that prototype.
- Mix = function(proto, a) {
- this.f = function() {
- return a
- }
- };
- var Thing = Class(
- function() {
- Class.attach(Mix, 1);
- });
- var t = new Thing;
- t.f() // --> 1
(instance).base每个用Class创建的类构造的对象都有一个base用于调用基类方法。类似这样:
Each object constructed by a Class-defined class contains the base as a base-method invoker. Like this:
- var A = Class( function(p) {
- this.f = function(t) {
- return t
- }
- });
- var B = Class( function(p) {
- Class.base(A);
- this.f = function(t) {
- return 'x' + this.base('f', t)
- };
- });
- var obj = new B();
- obj.f(1); // --> x1
传入给base的第一个参数是要调用的基方法名,接着是参数。base会搜索其基类,如果它定义了 指定的方法,就执行之,否则继续向上,直到确认在所有基类中都找不到为止。
First argument passed into base is the method name we want to invoke, then "actual" arguments. base will search its base class, invoke the specified method if the base class defined it, or continue going up until it confirmed the method is absent in all base class definitions.
- var A = Class( function(p) {
- this.f = function(t) {
- return t
- }
- });
- var B = Class( function(p) {
- Class.base(A);
- });
- var C = Class( function(p) {
- Class.base(B);
- this.f = function(t) {
- return 'x' + this.base('f', t)
- }
- this.g = function() {
- return this.base('g')
- }
- });
- var obj = new C();
- obj.f(1); // --> x1
- obj.g(); // --> Error: Method "g" absent
想象一下我们在书写一个迷宫程序。迷宫由若干cell组成,我们的目的是看有没有去出口的路径。这种问题很适合用回溯 法,算法的框架大体如下:
Imagine that we're writing a maze program. A maze consists of some cell, and we're going to find out whether the way to the exit exists. This problem is suit for backtracking. The algorithm looks like this:
- var found = false, steps = 0;
- function searchCell(position) {
- position.visited = true;
- if (position == maze.exit) {
- found = true;
- return
- };
- steps += 1;
- var neighbors = position.getNeighbors();
- for (var each in neighbors) if (!neighbors[each].visited) {
- searchCell(neighbors[each]);
- if (found) return;
- }
- steps -= 1;
- }
- searchCell(maze.start)
steps很好地说明了运行时覆写的原理——当搜索一个未访问的cell时,把它加1,表示 “走一步”;而回溯的时候,则把它减1,表示“退回”。这样,如果你搜索地图无果,那么steps还是0。
steps explained the mechanism of runtime overwriting well -- when searching one unvisited cell, increase it, means "one step"; when backtracking, decrease it, means "go back". Therefore, if the way does not exist, steps equals to 0.
运行时覆写的基本思路就是——当进入方法,修改某个东西;当退出方法,则把它改回来。
Basic principles of Runtime overwritting is Change something when enter the method, and change it back when exit.
priv你肯定很好奇调用priv的时候是怎么知道要取那个对象的保护成员的。要知道我们压根没有给priv传this指 针。实际上,priv取的是一个叫bound的对象的保护成员——bound则 是在调用对象方法的时候覆写成传入那个方法的this指针的。
You will be curious about how priv knows which object's protected members will be accessed. We never pass this pointer to priv. Actually, priv accesses the protected members of an object named "bound". "bound" is overrited to this pointer when invoking a method.
emop中,每个类定义的方法都被包裹,秘密在wrapProtected中。它的代码是:
- var bound;
- // ........
- var wrapProtected = function(method) {
- return function() {
- var hold = bound;
- bound = this;
- try {
- var ret = method.apply(this, arguments);
- } finally {
- bound = hold;
- return ret;
- }
- }
- }
- // ........
- Clz.prototype[each] = wrapProtected(def[each]);
因为不能给priv直接传this(否则要他还有何意义),wrapProtected就 做了一个有趣的事情——在对象调用方法之前,把bound设置成传入的this指针,同时做备份; 而当退出时,则把bound再改回来。这么一来二去,method调用时可 以正确找到保护成员,而结束后则像什么都没发生一样。 priv
Because we can't pass this to priv explicitly, wrapProtected did something interesting. Before the "real" method's invocation, change bound to passed this pointer, also backup it; After the method invoked, change bound back. With this process, when the "real" method is running, priv works correctly, and, when it ended, it seems nothing happened to priv and bound.
try ... finally保证了即使method发生异常,bound也 能改回来。当然,这会造成一点性能损失。
try ... finally ensured that even method throws an exception, bound will be changed back. Obviously, it will slow down the progeam a little.
Class.base和Class.attach的原理相似,这里就不深究了。各位可以看代 码研究。
Class.base and Class.attach works in the same mechanism. You can read the code above.
basebase中使用的技术最为复杂——因为这次覆写的就是它自己。this.base在它自己调 用时,基类方法调用前覆写,基类方法调用后改回。
Techniques used in base is the most complicated, becaust it will overwrite itself. this.base overwrites itself after it is invoked, and before base method's invocation; and change it back after base method exits.
base搜索基方法依赖在类上维护的baseConstructor属性,它直接指向基类。用于覆写的base由一个叫mgBaseGen的函数生 成,代码是:
base's searching depends on the baseConstructor property of classes, which points to it's class. bases used to overwrite is generated by function mgBaseGen:
- var mgBaseGen = function(bcl, original) {
- return function(nname) {
- var c = bcl, rv;
- while (c && !c.prototype.hasOwnProperty(nname)) c = c.baseConstructor;
- if (!c) throw new Error('Cannot find base class with specific method');
- this.base = mgBaseGen(c.baseConstructor, this.base);
- try {
- rv = c.prototype[nname].apply(this, Array.prototype.slice.call(arguments, 1));
- } finally {
- this.base = original;
- };
- return rv;
- };
- };
mgBaseGen接受两个参数,一个是搜索方法的起点bcl,另一个是备份original。 在3-5行,沿着baseConstructor链搜索某个合适的类c,包含nname指 定的方法;接着,把this.base覆写成以c的基类为起点的新base。 然后,调用基类方法。调用完毕,则把this.base改回original,清除痕迹;最后,返 回值。
mgBaseGen accepts two parameters, ont is the searching start, bcl, the other is the backup, original. In line 3-5, generated base method searches the class c defines specified method method; then overwrite the this.base method by a new base with c.baseConstructor as searching start. Then, invoke the found base method and change this.base back.
这样,this.base就以一种神奇的方式工作——如果基类方法还要调用更“基类”的方法的话,this.base就 会站在更深的地方搜索方法。而当基类方法调用完成时,this.base就像没改过一样。
In this way, this.base works magically -- if the base method needs to invoke a "baser" method, this.base will start searching the method at a "deeper" place. But when the base method is exited, this.base looks unchanged.
this.base加入到原型中使用下面的代码——这几乎不用解释:
Adding this.base into prototype uses following code -- explaining is needless:
- Clz.prototype.base = function(name) {
- var c = Clz.baseConstructor, rv, cler = arguments.callee.caller.caller;
- var original = this.base;
- this.base = mgBaseGen(c, original);
- try {
- rv = this.base.apply(this, arguments);
- } finally {
- this.base = original;
- };
- return rv;
- };
在类定义中我们用“this.method = function(){...}”定义方法,但是,这种定义法是如何变 成一个构造器的呢?事实上在Class中,我们把定义给new了一次:
In class definitions, we use "this.method = function(){...}" to define methods. But how did the class definition come into a constructor. In fact, we constructed the definition once in Class:
- Class = function(definition, proto) {
- // ...
- var ctor, def = new Definition(priv);
- if (def.initalize instanceof Function) {
- ctor = wrapProtected(def.initalize);
- } else {
- ctor = NULLFUNC;
- };
- delete def.initalize;
- // create class
- var Clz = function() {
- registerProtecteds(this);
- return ctor.apply(this, arguments);
- };
- // ...
- }
def对象是“new”定义的产物,接着,如果它包含initalize方 法,则把包裹它作为“初始化器”,否则,就用空函数。生成的构造器Clz实际上包含了两步,一个是注册保护成员(见下一节), 另一个则是执行初始器。
The def object is the result of constructing definition, and then, if def contains initalize method, wrap it by wrapProtected and set the initalizer (ctor) to it; if not, set it to the empty function. Generated constructor Clz contains 2 steps: registering protected menber (see the selection below), and executing ctor.
原型的绑定在下一步:
Prototype is bound in the next:
- //bind prototype
- if (proto instanceof Function || NClassBase instanceof Function) {
- if (proto instanceof Function) {
- Clz.prototype = new proto;
- Clz.baseConstructor = proto;
- } else if (NClassBase instanceof Function) {
- Clz.prototype = new NClassBase;
- Clz.baseConstructor = NClassBase;
- };
- Clz.prototype.base = function(name) {
- var c = Clz.baseConstructor, rv, cler = arguments.callee.caller.caller;
- var original = this.base;
- this.base = mgBaseGen(c, original);
- try {
- rv = this.base.apply(this, arguments);
- } finally {
- this.base = original;
- };
- return rv;
- };
- } else {
- if (proto) Clz.prototype = proto;
- else Clz.prototype = {};
- Clz.baseConstructor = Object;
- };
- proto = Clz.prototype;
这里检查了两处,一个是显式传入的proto,另一个是用Class.base注册的基类NClassBase。 如果proto是函数,则构造一个对象做原型,NClassBase同理。如果proto是 一个对象,则把Clz的原型直接赋予它。
We checked explicitly passed argument proto and NClassBase registered by Class.base. If proto is a function, the prototype of Clz will be the object constructed by proto. NClassBase is processed in like manner. If proto is an object, but not a function, then directly set Clz.prototype to it.
现在我们要深入priv,了解保护成员是如何实现的。
Now we will see the detail of priv, to know how protected members implemented.
- var priv = function(n, v) {
- if (!bound.hasOwnProperty('__protected')) return new Error('access denied');
- if (arguments.length > 1) return bound.__protected(CHECK, n, v);
- else return bound.__protected(CHECK, n);
- };
priv的实现异常简单——它调用……对象的__protected方法。等等,这个方法会不会把 保护成员泄密?实际上不会,因为有CHECK。CHECK是一个围在闭包里的“令牌”,外界几乎无 法获取。__protected方法是在这里注册的:
The implementation of priv looks very simple. It invokes ...... the __protected method of the object. But will this method betray its protected methods? Actually no, because there is a check. The constant CHECK is an token object contained in the outer closure and it's unaccessable outside. __protected was registered here:
- // Token
- var CHECK = {};
- // Empty function
- var NULLFUNC = function() {};
- // hasOwnProperty checker
- var HOPCHECKER = {};
- var registerProtecteds = function(o) {
- var protecteds = [];
- var p = function(checker, name, value) {
- if (checker !== CHECK) throw new Error('access denied');
- if (arguments.length > 2) return protecteds[name] = value;
- else if (HOPCHECKER.hasOwnProperty.call(protecteds, name)) return protecteds[name];
- };
- p.length = 0;
- p.toString = function() {
- throw new Error('access denied')
- };
- o.__protected = p;
- };
函数p的第一行干的就是检查CHECK,如果“令牌”不对,对不起,access denied。接下来的内容就很简单了,基本的hash操作。这里使用了一个小技巧,用HOPCHECKER的hasOwnProperty检 查protecteds的属性有无,防止覆写hasOwnProperty造成检测的错误。
What the first line of function p did is checking CHECK. if the token is wrong, then throw an access denied exception. Following contents are easy, basic hashtable operations.There is a small technique: checking property existance of protecteds by HOPCHECKER's hasOwnProperty, in order to avoid mistakes made by overwriting hasOwnProperty.
那么,registerProtecteds是何时“注册”到对象上的呢?答案在这里:
So, when does registerProtecteds "registers" to the object? The answer is here:
- var Clz = function() {
- registerProtecteds(this);
- return ctor.apply(this, arguments);
- };
Clz.prototype.method = function(){}定义方法 Clz.prototype.method = function(){...} is still avliablebase在不用Class定义的派生类中仍可使用,只需维护baseConstructor base is still avaliable in derived classes not defined by Class, only keeping baseConstructor needed.try ... finally造成调试不便 try ... finally will make debugging unconvient