<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>javascript创建对象的方式</title> <script type="text/javascript"> // 1. 通过字面量方式创建 var person = { name: "name", sayHi: function() { return this.name + "说话了"; } }; console.log(person.name); console.log(person.sayHi()); // 2. 通过构造函数方式创建 function Dog(name) { this.name = name; this.sayHi = function(content) { return this.name + "说话了" + content; }; this.auto = function() { console.log("执行这里"); } alert("这里的代码会在每一次new初始化实例对象的时候执行"); } var dog = new Dog("旺仔"); var dog1 = new Dog("旺仔"); dog.auto(); console.log(dog.name); console.log(dog.sayHi("狗叫。。。。")); // 3. 通过obj对象创建 var animal = new Object(); animal.name="晓得"; animal.age = 30; animal.sayHi = function(){ return "我是一个动物"; } console.log(animal.name); console.log(animal.sayHi()); </script> </head> <body> </body> </html>