原理:参数适配器说白了就是给出要带入数据字段的对应字段的默认值,一旦数据字段值不足,就取默认值补足。
[写法一]:直接返回
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>参数适配器1</title>
<script type="text/javascript">
//本地数据对象
var obj1 = {
name:'javascript高级编程2',
age:26,
price:45,
}
function doSomeThing(obj){
var _adapter = {//这个就是参数适配器,说白了就是参数默认值集合
name:'javascript高级编程',
author:'张小小',
age:28,
price:59,
press:'人民邮电出版社'
}
for(var i in _adapter){
_adapter[i] = obj[i] || _adapter[i];
}
return _adapter;
};
//测试用实例引用
var o = doSomeThing(obj1);
alert(o.name);
//本例已经通过验证
</script>
</head>
<body>
</body>
</html>
[写法一]:闭包返回
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>参数适配器1</title>
<script type="text/javascript">
//本地数据对象
var obj1 = {
name:'javascript高级编程2',
age:26,
price:45,
}
function doSomeThing(obj){
var _adapter = {//这个就是参数适配器,说白了就是参数默认值集合
name:'javascript高级编程',
author:'张小小',
age:28,
price:59,
press:'人民邮电出版社'
}
for(var i in _adapter){
_adapter[i] = obj[i] || _adapter[i];
}
return (function(){
return _adapter;
})();
};
//测试用实例引用
var o = doSomeThing(obj1);
alert(o.author);
//本例已经通过验证
</script>
</head>
<body>
</body>
</html>
[写法三]:匿名对象返回
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>参数适配器1</title>
<script type="text/javascript">
//本地数据对象
var obj1 = {
name:'javascript设计模式与开发实践',
age:26,
price:45,
}
function doSomeThing(obj){
var _adapter = {//这个就是参数适配器,说白了就是参数默认值集合
name:'javascript高级编程',
author:'张小小',
age:28,
price:59,
press:'人民邮电出版社'
}
return {
dataobj:function(){
for(var i in _adapter){
_adapter[i] = obj[i] || _adapter[i];
}
return _adapter;
}
}
};
//测试用实例引用
var o = doSomeThing(obj1);//o变量引用的是返回的匿名对象
alert(o.dataobj()['name']);//dataobj是匿名对象中的方法,只有执行一次后才会得到方法中的返回值_adapter,所以就有了dataobj()['name']的写法
//本例已经通过验证
</script>
</head>
<body>
</body>
</html>