//创建对象的几种方式
//第一种
var student1 = {};//空对象
var student2 = {name:"Burgess",sex:"男",show:function(name){ //对象student2
return ("大家好,我叫"+name);
}
};
alert(student2.show("Burgess"));
//第二种
var student3 = new Object();
student3.name = "Burgess";
student3.sex = "男";
student3.age = "25";
student3["My address"] = "SuZhou"; //这也是对象的属性
student3.showMessage = function (name,age,address) {
address = student3["My address"];
return ("大家好,我叫" + name + ",我今年" + age + ",我来自" + address);
}
alert(student3.showMessage("Burgess", 25,""));
//第三种
var student4 = Object.create({
name: "Burgess", age: "25", showMessage: function (name,age) {
return ("大家好,我叫" + name + ",我今年" + age);
}
});
alert(student4.showMessage("Burgess", "25"));
//读取属性值和修改属性值
student4.age = 29;//修改属性值
var age = student4.age//获取属性值
alert(student4.age + "岁");
//检测属性是否存在的四种方式
//第一种
var student6 = { x: 10 };
if ("x" in student6) { //in运算符,左边是属性名(字符串),右边是对象,返回true or false
alert("对象中存在该属性");
}
//第二种
var student7 = { y: 10 };
var result=student7.hasOwnProperty("x");// 对象的hasOwnProperty,检测对象是否存在属性,返回true orfalse
if (result) {
alert("对象中存在该属性");
} else {
alert("对象中不存在该属性");
}
//第三种
var student8 = { y: 10 };
var result = student8.propertyIsEnumerable("x");// 对象的propertyIsEnumerable,检测对象是否存在属性,返回true orfalse
if (result) {
alert("对象中存在该属性");
} else {
alert("对象中不存在该属性");
}
//第四种
var student9 = { y: 10 };
if (student9.x!=undefined) { //最简单的方法
alert("对象中存在该属性");
} else {
alert("对象中不存在该属性");
}
//删除属性值
delete student3.age;
alert(student3.age);
//遍历对象属性
var props="";
for (var p in student3) { // p 为属性名称
if (typeof (student3[p]) == "function ") {
student3[p]();
} else { // p 为属性名称,obj[p]为对应属性的值
props += p + "= " + student3[p] + ",";
}
}
// 最后显示所有的属性
alert(props);
//对象的方法
var student11 = {
name: "",
age: 12,
sex:"男"
}
var result11 = student11.age.toString();//将对象值转换成字符串
var result12 = student11.age.toLocaleString();//返回对象的本地化字符串
var result13 = JSON.stringify(student11.age);//转化为json字符串
var result14 = student11.age.valueOf();//返回对象的原始值
alert(result11);
alert(result12);
alert(result13);
alert(typeof(result14));