1.字面量创建对象
var 对象名 = { } //创建格式
例子:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script>
var s={
name : '可可', //函数体中的name,type,age,colour均为属性的
type : '阿拉斯加', 添加方式(属性名 : 添加内容)
age : '5岁',
colour : '棕红色',
skill : function () { //skill为方法的添加方法
console.log( '汪汪汪,演电影'); (方法名 :function () {函数体 }
}
}
console.log(s.name); //调用属性的方法有两种一种为
console.log(s.age); (对象名 .属性名)或者是
console.log(s['type']); (对象名['属性名'])
console.log(s['colour']);
s.skill(); //调用方法的方法: 对象名.方法名();
</script>
</head>
<body>
</body>
</html>
2.new关键字Object创建对象
var 对象名 = new Object (); //创建格式
例子:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script>
var obj = new Object ();
obj.name = '鸣人';
obj.sex = '男';
obj.age = '19岁';
obj.skill = function () {
return '影分身术';
}
console.log(obj.name);
console.log(obj.sex);
console.log(obj.age);
console.log(obj.skill());
</script>
</head>
<body>
</body>
</html>
代码说明:
给对象增加属性: 对象名 . 属性名 = 输入内容 ;
例如: obj .name = ‘鸣人’;
给对象增加方法: 对象名 . 方法名 = function () { 函数体};
例如: obj.skill = function () {
return ‘ 影分身术’ ;
}
3.构造函数创建对象(可以创建多个对象)
function 函数名 (参数1,参数2,参数3····) {
this. 属性 = 参数1;
this. 属性 = 参数2;
this. 属性 = 参数3;
this. 方法 = function () {函数体 };
}
var 对象名 = new 函数名 (参数1,参数2,参数3···); //只需要改变对象名和参数则可以
创建多个对象
例子:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script>
function Charcter (name,type,blood,attack) {
this.name = name;
this.type = type;
this.blood = blood;
this.attack =attack;
}
var Lianpo = new Charcter('廉颇','力量型','500血量','近战');
var Houyi = new Charcter('后裔','射手型','100血量','远程');
console.log(Lianpo.name);
console.log(Lianpo.type);
console.log(Lianpo.blood);
console.log(Lianpo.attack);
console.log(Houyi.name);
console.log(Houyi.type);
console.log(Houyi.blood);
console.log(Houyi.attack);
</script>
</head>
<body>
</body>
</html>