JavaScript-19.JS中产生的对象以及批量产生对象
2017-03-05 本文已影响97人
IIronMan
1.JS产生一个对象
<!--1.创建一个dog对象-->
var dog = {
name:'阿尔法',
age:10,
height:1.55,
dogFriends:['hhh','jj'],
eat:function (something) {
console.log(this.name+'吃'+something);
},
run:function () {
console.log('跑');
}
};
console.log(dog.name);
dog.eat('五花肉');
2.JS产生多个对象
// 创建构造函数
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>5.创建构造函数</title>
<script>
// 创建构造函数
var Dog = function () {
this.name = null;
this.age = null;
this.dogFriends = [];
this.height = null;
this.eat = function (someThing) {
console.log(this.name + '吃' + someThing)
}
this.run = function (somewhere) {
console.log(this.name + '跑' + somewhere)
}
};
// 批量产生对象
var dog1 = new Dog();
dog1.name = '小花';
dog1.age = '15';
dog1.dogFriends = ['11','22'];
dog1.height = '1米55';
dog1.eat('骨头');
dog1.run('北京');
var dog2 = new Dog();
dog2.name = '小花';
dog2.age = '15';
dog2.dogFriends = ['33','44'];
dog2.height = '1米34';
dog2.eat('牛肉');
dog2.run('上海');
</script>
</head>
<body>
</body>
创建构造函数