JavaScript在线编辑与测试地址:
JavaScript 中的所有事物都是对象:字符串、数值、数组、函数...(内置对象),可以分为内置对象与自定义对象(通过对象构造器方式生成的)
分为内置对象与自定义对象:
javaScript中自定义对象创建的三种方法:
1.字面量(literals)的创建方式:o1 = { key1 : value1 , key2 : value2}; 参考eg1
2.object.create()方式:o1 = object.create(null); eg2
3.对象构造器的方式:o1 = new object(); eg3
对象构建例子
eg1:字面量方式
{}中由若干键值对组成,键值对之间用逗号分隔,key值必须为字符串类型,可以省略引号(""),value可以为任何数据类型如number,function都可以
var person = {age:25, name:"tom", eat:function() { return "eatDinner"; }, changeName: function(name) { this.name = name; } };var testAge = person.age;var testEat = person.eat();person.changeName("LiMing");var testChangeName = person.namedocument.write(testAge + testEat + testChangeName);
eg2:object.create(null)方式
var person=new Object();person.firstname="Bill";person.lastname="Gates";person.age=56;person.eyecolor="blue";document.write(person.age + " " + person.eyecolor);
eg3:对象构造器方式
function person(firstname,lastname,age,eyecolor){this.firstname=firstname;this.lastname=lastname;this.age=age;this.eyecolor=eyecolor;}var myFather=new person("Bill","Gates",56,"blue");var myMother=new person("Steve","Jobs",48,"green");document.write(myFather.age + " " + myMother.age);
为对象添加属性:
var person=new Object();person.firstname="Bill"; //为已存的对象添加firstname属性person.lastname="Gates";person.age=56;person.eyecolor="blue";person.firstname = "tom"; //如果该属性已存在,则将之前的属性值覆盖了
为对象添加方法:
var person=new Object();person.fun = function(){return "方法";};person.fun2 = function(varName){return varName;}; function funName(){return 5;}person.fun3 = funName;document.write(person.fun() + " " + person.fun2(2) + " " + person.fun3());注意:如果在方法调用时误写成了person.fun,少加了括号的话,刚会照原样将方法的内容输出,而是去执行方法里面的内容:如上面写成person.fun,则结结果会输出function(){return "方法";},而不是输出内容:"方法"两个字,问:怎么来避免这种情况发生呢?