1.通过表达式创建
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <script> //1.通过表达式创建对象 var per1 = { name:'苏凉', age:21, gender:'男', sayName:function(){ console.log(this.name) } }; console.log(per1); per1.sayName(); </script> </head> <body> </body> </html>
2.使用new关键字
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <script> //2.使用new关键字 var per2 = new Object(); per2.name = '苏凉'; per2.age = 21; per2.gender = '男'; per2.sayName = function(){ console.log(this.name) } console.log(per2); per2.sayName(); </script> </head> <body> </body> </html>
3.使用工厂模式
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <script> //3.使用工厂模式创建 function person(name,age,gender){ var obj = new Object(); obj.name = name; obj.age = age; obj.gender = gender; obj.sayName = function(){ console.log(this.name) } return obj; } var per3 = person('苏凉',21,'男'); console.log(per3); per3.sayName(); </script> </head> <body> </body> </html>
4.使用构造函数
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <script> //4.使用构造函数创建 function Person(name, age, gender){ this.name = name ; this.age = age ; this.gender = gender; } Person.prototype.sayName = function(){ console.log(this.name) } var per4 = new Person('苏凉',21,'男'); console.log(per4); per4.sayName(); </script> </head> <body> </body> </html>
运行结果: