编程: 创建对象的方式(字面量或构造函数)
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>js中创建对象的方法</title> <script> //1. 直接创建对象 ,字面量 let obj1 = { name: 'jimmy', sex:'female',age:18,address:'西安'}; //测试 document.write(obj1.name,obj1.sex,obj1.age,obj1.address); // 2.利用 Object 创建对象实例 let obj2 = new Object(); obj2.name = 'jimmy'; obj2.sex = 'female'; obj2.age = 18; obj2.address = 'BeiJing'; //测试 alert(obj2.address); //3.利用工厂模式函数创建,可以创建多个类似对象 function createStu(name,age) { let obj3 = new Object(); obj3.name = name; obj3.age = age; return obj3; } let student1 = new createStu('core',21); console.log(student1.name +':'+ student1.age); //4.用构造函数+原型对象模式 创建对象 function Student(name,age) { //构造函数的名字,应首字母大写,以区别普通函数 this.name=name; this.age=age; this.friends= ['jimmy','peter']; } //把方法写入proto Student.prototype ={ sayName:function () { return this.name; } }; let student2 = new Student('core',30); student2.friends.push('zola'); console.log(student2.friends); console.log(student2.sayName()); </script> </head> <body> </body> </html>
点击 "运行实例" 按钮查看在线实例