01. Object constructor mode
Mode 1: Object constructor mode
*Routine: Create an empty Object object before dynamically adding attributes/methods
*Scenario applicable: start with indeterminate object internal data
*Question: Too many statements
<script type="text/javascript"> // Alone?: name:"Tom", age: 12 var p = new Object() p = {} p.name = 'Tom' p.age = 12 p.setName = function (name) { this.name = name } p.setaAge = function (age) { this.age = age } console.log(p) </script>
02. Object Literal Quantity
Mode 2: Object Literal Quantity Mode
*Routine: Create objects using {} while specifying properties/methods
*Scenario applicable: Internal data within the object is deterministic at the start
*Problem: If multiple objects are created, there is duplicate code
<script type="text/javascript"> var p = { name: 'Tom', age: 23, setName: function (name) { this.name = name } } console.log(p.name, p.age) p.setName('JACK') console.log(p.name, p.age) var p2 = { name: 'BOB', age: 24, setName: function (name) { this.name = name } } </script>
03. Factory Mode
Mode 3: Factory Mode
*Routine: Dynamically create objects through factory functions and return them
*Scenario applicable: multiple objects need to be created
*Problem: Objects do not have a specific type, they are all Object types
<script type="text/javascript"> // Factory function: A function that returns a required data function createPerson(name, age) { var p = { name: name, age: age, setName: function (name) { this.name = name } } return p } var p1 = createPerson('Tom', 12) var p2 = createPerson('JAck', 13) console.log(p1) console.log(p2) </script>
04. Custom constructor mode
Mode 4: Custom constructor mode
*Routine: Custom constructor to create objects from new
*Scenario applicable: multiple types of identified objects need to be created
*Problem: Every object has the same data, wasting memory
<script type="text/javascript"> function Person(name, age) { this.name = name this.age = age this.setName = function (name) { this.name = name } } var p1 = new Person('Tom', 12) var p2 = new Person('Tom2', 13) console.log(p1, p1 instanceof Person) </script>
05. Constructor + Prototype Combination Mode
Mode 5: Constructor + Prototype Combination Mode
*Routine: Custom constructors, properties initialized in functions, methods added to prototypes
*Scenario applicable: multiple types of identified objects need to be created
<script type="text/javascript"> function Person (name, age) { this.name = name this.age = age } Person.prototype.setName = function (name) { this.name = name } var p1 = new Person('Tom', 12) var p2 = new Person('JAck', 23) p1.setName('TOM3') console.log(p1) Person.prototype.setAge = function (age) { this.age = age } p1.setAge(23) console.log(p1.age) Person.prototype = {} p1.setAge(34) console.log(p1) var p3 = new Person('BOB', 12) p3.setAge(12) </script>