/** *创建对象方式一,直接通过大括号创建 */ var Student1 = {}; Student1.name ="张三"; Student1.age =18; Student1.setName =function (name){ this.name = name; }; Student1.getName =function(){ return this.name; } console.log(Student1); //结果:{ name: '张三', age: 18, setName: [Function], getName: [Function] } Student1.setName("zhangsan"); console.log(Student1.getName()); //结果:zhangsan /** *创建对象方式二:大括号创建并设置属性 */ var Student2 = { name : "张三", age : 18, setName : function(name){ this.name = name; }, getName : function(){ return this.name; } }; console.log(Student2); //结果:{ name: '张三', age: 18, setName: [Function], getName: [Function] } Student2.setName("zhangsan"); console.log(Student2.getName()); //结果:zhangsan /** *创建对象方式三:构造方法 */ function Student3(name,age){ this.name = name; this.age = age; this.setName = function(name){ this.name = name; }; this.getName = function(){ return this.name; } } var stu = new Student3("张三",18); console.log(stu); //结果:{ name: '张三', age: 18, setName: [Function], getName: [Function] } stu.setName("zhangsan"); console.log(stu.getName()); //结果:zhangsan /** *创建对象方式三:构造方法 + 属性 */ function Student4(name,age){ this.name = name; this.age = age; } Student4.prototype.setName =function(name){ this.name = name; } Student4.prototype.getName=function(){ return this.name; } var stu = new Student4("张三",18); console.log(stu); //结果:{ name: '张三', age: 18 } stu.setName("zhangsan"); console.log(stu.getName()); //结果:zhangsan