创建一个类Person

创建一个类Person,包含以下属性:姓名(name)、年龄(age)、朋友(friends数组)、问候(sayhi方法,输出问候语,例如:“你好!”)、交朋友(addFriend方法,向friends里添加一个值),然后创建两个此类的实例:“小张“,22,[“小李”,”小王”],”你好!”,”James”,”James”,24,[“Ann”,”Billy”],”Hello!”,”小张”

function Person(props){
this.name=props.name||'匿名';
this.age=props.age||20;
this.friends=props.friends||'无';
}
Person.prototype.sayhi=function(){
console.log("你好!"+this.name);
}
Person.prototype.addFriend=function(newf){
this.friends.push(newf);
console.log(this.friends);
}
function createPerson(props) {
    return new Person(props || {});
}
var xiaozhang=createPerson({
name:'小张',
age:22,
friends:["小李","小王"]
});
xiaozhang.sayhi();//你好!小张
xiaozhang.addFriend('James');//["小李", "小王", "James"]

posted @ 2016-05-17 14:25  害羞熊5  阅读(1024)  评论(0编辑  收藏  举报