ThinkChat2.0新版上线,更智能更精彩,支持会话、画图、阅读、搜索等,送10W Token,即刻开启你的AI之旅 广告
```html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> </head> <body> <!-- 创建对象的写法有以下7种,其中第6、7性能是最好的,但不一定适用,根据情况而定选择哪种写法 --> <script type="text/javascript"> // 1. 使用Object对象 var person = new Object(); person.name = "Jack"; person.getName = function() { console.log(this.name); } // 调用语法 console.log(person.name); // Jack,或person["name"] person.getName(); // Jack,或person["getName"] </script> <script type="text/javascript"> // 2. 通过字面量来创建 var person = { name: "Jack", getName: function() { console.log(this.name); } } // 调用语法 console.log(person.name); // Jack,或person["name"] person.getName(); // Jack,或person["getName"] </script> <script type="text/javascript"> // 3. 工厂函数 function createPerson(name) { return { name: name, getName: function() { console.log(this.name); } } } // 调用语法 var person = createPerson("Jack"); console.log(person.name); // Jack,或person["name"]; person.getName(); // Jack,或person["getName"]; </script> <script type="text/javascript"> // 4. 构造函数创建 function Person(name) { this.name = name; this.getName = function() { console.log(this.name); } } // 调用语法 var person = new Person("Jack"); console.log(person.name); // Jack,或person["name"] person.getName(); // Jack,或person["getName"]() </script> <script type="text/javascript"> // 5. 构造函数创建,但把共享的属性/函数放在构造函数外部定义 function Person(name) { this.name = name; this.getName = getName; } function getName() { console.log(this.name); } // 调用语法 var person = new Person("Jack"); console.log(person.name); // Jack,或person["name"] person.getName(); // Jack,或person["getName"]() </script> <script type="text/javascript"> // 6. 将共享的属性/函数放在原型对象prototype中,这也是最好的方法 function Person(name) { this.name = name; this.getName = function() { console.log(this.name) } } // 将共享的属性/函数放在prototype原型对象上 Person.prototype.height = "30"; Person.prototype.getHeight = function() { console.log(this.height); } // 调用语法 var person = new Person("Jack"); console.log(person.name); // Jack,或person["name"] person.getName(); // Jack,或person["getName"]() console.log(person.height); // 30,或person["height"] person.getHeight(); // 30,或person["getHeight"]() </script> <script type="text/javascript"> // 7. 更简单的原型写法 function Person(name) { this.name = name; this.getName = function() { console.log(this.name) } } Person.prototype = { constructor: Person, height: "30", getHeight: function() { console.log(this.height); } } // 调用语法 var person = new Person("Jack"); console.log(person.name); // Jack,或person["name"] person.getName(); // Jack,或person["getName"]() console.log(person.height); // 30,或person["height"] person.getHeight(); // 30,或person["getHeight"]() </script> </body> </html> ```