前面说了,接下来我想从事前端开发的工作,以前也接触过前端内容,但是有些时间没有看它了,于是,便再找一些资源重新回顾一遍,本来在纠结这么基础的内容到底要不要放上来,想想还是放上来吧,分享给一些刚入门的小伙伴们,虽然这一块讲解的内容网上也很多,但最终也是为了方便自己回顾以及后续可以回来重温小细节吧。
对象
1.自定义对象:
如果对象包含了空格,减号,关键字等,必须加上引号,第二种方式属性只能使用[]来访问。
var obj = { name:'TOM', age:18 };
或
var obj = new Object();
obj.name = 'TOM';
obj["age"] = 18;
[]中必须是string类型,单/双引号均可
2.自定义对象的遍历
var emp = {name:'Fan Fan',age:18};
for(var attrName in emp){
console.log(attrName + ':' + emp[attrName]);
}
(1)for in 遍历对象的属性并没有特定的顺序;
(2)只能遍历出用户自定义的属性,不能枚举出预定义的属性和方法
3.属性访问错误
//访问未声明的变量
console.log(emp0); //ReferenceError
//访问未声明的属性
var emp1 = {};
console.log(emp1.ename); //undefined
//访问未声明的属性的成员
var emp1 = {};
console.log(emp1.ename.length); //TypeError
如何使用错误处理结构try..catch..语句块来捕捉抛出的错误,来避免程序异常终止
try{
console.log(emp1);
}
catch(RefenceError)
{
console.log('RefenceError');
}
4.检查属性
(1)使用in关键字
console.log('ename' in emp1); // ture/false
属性名必须加上引号
(2)使用对象的hasOwnProperty()方法
console.log(emp1.hasOwnProperty('ename'));
(3)使用undefined判断
console.log(emp1.ename === undefined); // true表示未定义
(4)在条件语句中直接判断
if(emp1.ename){console.log('ename属性存在');}
函数
1.定义方法
var rect1 = {
width:20,
height:10,
getSize:function(){
return width*height;
},
getC:c //不能写成为c(),c函数返回的值赋值给getC
};
function c(){
return 2*(this.width + this.height);
};
2.调用方法
var circle1 = {
radius:undefined,
setRadius:function(radius){
this.radius = radius;
},
getSize:function(){
return Math.PI*this.radius*this.radius;
}
};
circle1.setRadius(2);
console.log(circle1.getSize());
this.radius = radiu 这句赋值不能直接赋值成 radius = radius,毕竟,两个对象是不一样的。