<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>javascript创建对象的不同方式</title> <script> // 1. 工厂模式:缺点是实例无法追踪到对象 function person(name,age){ var obj = new Object(); obj.name = name; obj.age = age; obj.sayHi = function(){ alert("sayHi"+obj.name); } return obj; } var p1 = person("lili",25) p1.sayHi(); console.log(p1.sayHi()); // 2. 构造函数模式:解决实例追踪对象的问题 function Dog(name,eat){ this.name = name; this.eat = eat; this.food = function(){ console.log(this.eat); } } // 3. 原型创建对象:节省空间,共享数据 function Animal(name){ this.name =name; } Animal.prototype.eat = function(){ console.log(this.name+"吃饭了"); } var a = new Animal("小黑"); a.eat(); </script> </head> <body> </body> </html>