天天看点

只遍历出JScript对象的expando属性

    由于JScript的prototype特性对对象的扩充非常的方便,所以我们在制作一些JScript类库的时候,一般都会使用prototype特性为对象添加方法,比如我们对Object进行如下prototype扩充:

只遍历出JScript对象的expando属性

Object.prototype.Clone = function() {};

只遍历出JScript对象的expando属性

Object.prototype.Call = function() {};

只遍历出JScript对象的expando属性

Object.prototype.OtherMethod = function(){};

    这个时候如果再使用Object作为map结构来使用,我们就会遇到遍历这个map的错误,看下面的代码:

只遍历出JScript对象的expando属性

var objMap = {};

只遍历出JScript对象的expando属性

objMap['abc'] = '1.abc';

只遍历出JScript对象的expando属性

objMap['def'] = '2.def';

只遍历出JScript对象的expando属性

objMap['ghi'] = '3.ghi';

只遍历出JScript对象的expando属性

objMap['jkl'] = '4.jkl';    

    遍历这个集合:

只遍历出JScript对象的expando属性

function DisplayMap(map)

只遍历出JScript对象的expando属性

{

只遍历出JScript对象的expando属性

    var values = [];

只遍历出JScript对象的expando属性

    for ( var key in map )

只遍历出JScript对象的expando属性

    {

只遍历出JScript对象的expando属性

        values.push(map[key]);

只遍历出JScript对象的expando属性

    }

只遍历出JScript对象的expando属性

    return values;

只遍历出JScript对象的expando属性

}

只遍历出JScript对象的expando属性

Display(objMap);

    我们发现,在values里的值居然是:function(){},function() {},function() {},1.abc,2.def,3.ghi,4.jkl。真是郁闷

只遍历出JScript对象的expando属性

! 其实这就是 for in 语句的效果,JScript也就是这么设计的,我们没有办法改变。那么我门能不能只取出objMap中expando进去的属性呢?

由于prototype属性的优先级很高,在对象实例生成的时候就expand到对象实例中去了。所以我们建立的任何一个对象,都会包含相同的prototype属性。这样一来就好办了,我们把objMap中的prototype属性找出来过滤掉就行了呗。参考代码如下:

只遍历出JScript对象的expando属性

function GetExpandoValues(map)

只遍历出JScript对象的expando属性
只遍历出JScript对象的expando属性
只遍历出JScript对象的expando属性

    var obj = new map.constructor();

只遍历出JScript对象的expando属性
只遍历出JScript对象的expando属性
只遍历出JScript对象的expando属性

        if ( obj[key] !== map[key] )

只遍历出JScript对象的expando属性

        {

只遍历出JScript对象的expando属性

            values.push(map[key]);

只遍历出JScript对象的expando属性

        }

只遍历出JScript对象的expando属性
只遍历出JScript对象的expando属性
只遍历出JScript对象的expando属性
只遍历出JScript对象的expando属性

GetExpandoValues(objMap);

    获得结果为:1.abc,2.def,3.ghi,4.jkl

只遍历出JScript对象的expando属性

本文转自博客园鸟食轩的博客,原文链接:http://www.cnblogs.com/birdshome/,如需转载请自行联系原博主。