一.创建对象
创建对象的方式有三种:
- 通过Object构造函数
- 自定义构造函数
- 字面量创建对象
1.通过Object构造函数
var obj = new Object();
obj.width = 100;
obj.height = 200;
obj.area = function () {
return obj.width * obj.height;
};
obj.sideLength = function () {
return (obj.width + obj.height) * 2;
};
console.log('width:', obj.width, 'height:', obj.height, 'area:', obj.area(), 'sideLength', obj.sideLength());
// width: 100 height: 200 area: 20000 sideLength 600
如果对象直接调用一个内部未定义的变量,程序不会报错,此时该变量的值为undefined,如果是Java的话连编译都不会通过。
2.自定义构造函数
function Rectangle(width, height) {
this.width = width;
this.height = height;
this.area = function () {
return this.width * this.height;
};
this.sideLength = function () {
return (this.width + this.height) * 2;
};
}
var obj = new Rectangle(100, 200);
console.log('width:', obj.width, 'height:', obj.height, 'area:', obj.area(), 'sideLength', obj.sideLength());
// width: 100 height: 200 area: 20000 sideLength 600
console.log(obj instanceof Rectangle);// true
console.log(obj instanceof Object); // true
上面代码创建了Rectangle构造函数。构造函数和普通函数区别在于,构造函数名首字母大写,内部可以通过this关键字获取自己的属性,构造函数可以作为普通函数一样使用。JavaScript中可以使用instanceof关键字判断对象是否是某对象类型。
3.字面量创建对象
var obj = {};//空对象
var obj = {
width: 100,
height: 200,
area: function () {
return this.width * this.height;
},
sideLength: function () {
return (this.width + this.height) * 2;
}
};
console.log('width:', obj.width, 'height:', obj.height, 'area:', obj.area(), 'sideLength', obj.sideLength());
// width: 100 height: 200 area: 20000 sideLength 600
通过字面量创建对象格式和JSON类似,这种方法创建对象有个缺点就是对象的属性值需要在内部写死,不利于代码复用。
二.获取属性
获取对象属性的方法有两种:
- 通过对象 . 属性
- 通过对象[“属性名”]
通过对象点属性的方法获取变量,前面的代码已有体现,不在赘述。
第二种方式直接看下面代码
var obj = new Object();
obj.width = 100;
obj.height = 200;
obj.area = function () {
return obj.width * obj.height;
};
obj.sideLength = function () {
return (obj.width + obj.height) * 2;
};
console.log('width:', obj["width"], 'height:', obj["height"], 'area:', obj["area"](), 'sideLength', obj["sideLength"]());
// width: 100 height: 200 area: 20000 sideLength 600
可以通过这种方式和for in语法遍历对象的所有属性。
for(var key in obj){
console.log(key,":",obj[key]); //输出变量名:变量值
console.log(key,":",obj[key]());//输出变量名:函数值
}
人贵以恒,加油吧,少年! 如有问题,恳请指正。