JS Code
/*
练习2:
实现一个叫Man的类,包含attr, words, say三个方法。
*/
var Man;
//+++++++++++答题区域+++++++++++
Man =
function(o){
if(!(
this instanceof Man)){
//Man 方法作为普通函数被调用
return new Man(o);
}else{
//Man方法作为构造函数被调用
this.attr(o);
}
}
Man.prototype =
{
attr: function(k,v){
if(
typeof k ==='object'
){
for(
var i
in k)
this.attr(i,k[i]);
}else{
// 通过attr获取或设置的变量都为私有变量, 私有变量的变量名具有'_'前缀.
var k = '_'+
k;
// 设置参数的值
if (arguments.length === 2
){
this[k] =
v;
}
// 访问参数的值
var r =
this[k];
if (r === undefined || r ===
null){
r = '<用户未输入>'
;
}
return r;
}
},
words:function(str){
if(
this['wordsArr'] ===undefined ||
this['wordsArr'] ===
null){
this['wordsArr'] =
new Array();
}
this['wordsArr'
].push(str);
},
say:function(){
var limit =
this['_words-limit'
];
var emote =
this['_words-emote'
];
var str =
this['_fullname']+emote+":\""
;
for(
var i =0;i<limit;i++
){
str+=
this['wordsArr'
][i];
}
str+="\""
;
return str;
}
}
//+++++++++++答题结束+++++++++++
try{
var me = Man({ fullname: "小红"
});
var she =
new Man({ fullname: "小红"
});
console.group();
console.info("我的名字是:" + me.attr("fullname") + "\n我的性别是:" + me.attr("gender"
));
console.groupEnd();
/*------[执行结果]------
我的名字是:小红
我的性别是:<用户未输入>
------------------*/
me.attr("fullname", "小明"
);
me.attr("gender", "男"
);
me.fullname = "废柴"
;
me.gender = "人妖"
;
she.attr("gender", "女"
);
console.group();
console.info("我的名字是:" + me.attr("fullname") + "\n我的性别是:" + me.attr("gender"
));
console.groupEnd();
/*------[执行结果]------
我的名字是:小明
我的性别是:男
------------------*/
console.group();
console.info("我的名字是:" + she.attr("fullname") + "\n我的性别是:" + she.attr("gender"
));
console.groupEnd();
/*------[执行结果]------
我的名字是:小红
我的性别是:女
------------------*/
me.attr({
"words-limit": 3
,
"words-emote": "微笑"
});
me.words("我喜欢看视频。"
);
me.words("我们的办公室太漂亮了。"
);
me.words("视频里美女真多!"
);
me.words("我平时都看优酷!"
);
console.group();
console.log(me.say());
/*------[执行结果]------
小明微笑:"我喜欢看视频。我们的办公室太漂亮了。视频里美女真多!"
------------------*/
me.attr({
"words-limit": 2
,
"words-emote": "喊"
});
console.log(me.say());
console.groupEnd();
/*------[执行结果]------
小明喊:"我喜欢看视频。我们的办公室太漂亮了。"
------------------*/
}catch(e){
console.error("执行出错,错误信息: " +
e);
}
转载于:https://www.cnblogs.com/-gap/archive/2012/06/28/2568610.html
相关资源:JAVA上百实例源码以及开源项目