//JS仿Python的from …… import ……方法将序列化对象的元素转换为(全局)变量
//也跟PHP数组中的list()方法功能相似
//没事写的玩,也许没有什么实际应用价值
var $object = {};
$object.from = function(_class) {
//if(_class && typeof (_class == "object")) {
this.class = _class;
return this;
//}
}
$object.import = function() {
for (var i=0; i
if(window[arguments[i]]) delete window[arguments[i]];
//alert(arguments[i]+"=>"+this.class[arguments[i]]);
window[arguments[i]] = this.class[arguments[i]];
}
}
//测试一:序列化对象
var test = {
name : "pandao",
work : "Web Designer",
fn : function(str) {
alert(str);
}
};
//$object.from(test).import("name", "work", "fn");
//alert("name=>"+name+", work=>"+work);
//fn("speech");
//测试二:数组对象
var test2 = [];
test2['name'] = "Tome";
test2['work'] = "Programmer";
test2['fn'] = function(str) {
alert(str);
};
//$object.from(test2).import("name", "work", "fn");
//alert("name=>"+name+", work=>"+work);
//fn("run");
//测试三:JS类对象
function testClass() {
this.name = "testClass";
this.version = "V1.0";
}
//公共静态方法
testClass.getVersion = function() {
alert(this.version);
return this;
};
//公共方法
testClass.prototype = {
add : function() {
alert("testClass.add()");
return this;
},
remove : function() {
alert("testClass.remove()");
return this;
}
//getVersion : function() {
//alert("version=>"+this.version);
//return this;
//}
};
var test3 = new testClass();
$object.from(test3).import("name", "version", "add", "remove", "getVersion");
alert("name=>"+name+", version=>"+version);
add();
remove();
getVersion(); //不这样调用公共静态方法,会出错了,暂时没想到解决方法,求教,错误信息:Uncaught TypeError: Property 'getVersion' of object [object Window] is not a function
后话:
PHP.JS 是一个开源的JavaScript 库,它尝试在JavaScript 中实现PHP 函数,它有实现PHP的list()方法。http://phpjs.org/