前些日子关注到了Javascript内核对对象内点语法的解析机制的一点点了解,为此本人在这里总结一下,也顺便up两个有点意思的Javascript方法。
Javascript的对象中如果遇到的点符号“.”,就会首先检查它全部包含的方法和属性,直到检查到点符号后面指定的方法或者属性。从这点出发,如果对象中嵌套的级别越多,这对频繁操作对象中的属性和方法就非常影响执行效率了。
下面是一个using方法,这个跟C#里的using方法的调用方式类似:
[javascript]
using(LIB.dom.classes).behavior(function(){
this.add=function(c){
this.classname=c;
}
//……
}
//它还有另外一种调用方式:
using(LIB.dom.classes,function(){
this.add=function(c){
this.classname=c;
}
//……
});
//using上面的两种方式可以互换操作,就是对同一个对象可以在两种方式中使用,比如:
//LIB.namespace是我接下来要说明的一个函数
LIB.namespace("dom.event");
using(LIB.dom.event,function(){
this.show=function(){
alert("Hello");
};
});
using(LIB.dom.event).behavior(function(){
this.show();
});
[/javascript]
现在我们来看看namespace方法的使用,namespace的作用已经不是什么新鲜事了,很多库中都使用了这种操作方法,比如Google的closure-library库中就大量使用了这种操作方式。上面的LIB.namespace(“dom.event”)调用之后,就会添加到LIB对象中作为命名空间,一级一级的添加。下面是源码:
[javascript]
try {LIB} catch (e) { LIB = {}}
LIB.namespace = function(s){
var names = s && typeof s.split === "function" ? s.split(".") : [];
var current=LIB;
for(var i=0,l=names.length;i<l;i++){
if(!current[names[i]]){
current[names[i]]={};
}
current=current[names[i]];
}
};
(function(global){
function _u(obj, fn){
fn ? fn.call(obj) : this.o = obj;
}
global.using = function(o, f){
if (f) {
return _u(o, f);
} else {
_u.prototype.behavior = function(f){
f.call(this.o);
}
return new _u(o);
}
}
})(this);
[/javascript]