JS factory method to create objects, constructor to create objects

Factory way to create objects

Use the factory method to create objects
Through this method, objects can be created in large quantities

<script>
        function createPerson(name, age, gender) {
     
     
            //创建一个新对象
            var obj = new Object();
            //向对象中添加属性
            obj.name = name;
            obj.age = age;
            obj.gender = gender;
            obj.sayName = function () {
     
     
                alert(this.name);
            }
            // 将新对象返回
            return obj;
        }
        var obj1 = createPerson("TOM", 16, "男");
        var obj2 = createPerson("JIM", 18, "女");
        obj1.sayName(); 
        //TOM
 </script>

but
insert image description here
insert image description here
insert image description here

Constructor

  • There is no Person type, you can create a constructor to create a Person object
  • A constructor is an ordinary function, and its creation method is no different from that of an ordinary function. It is customary to capitalize the first letter
  • Ordinary functions are called directly, and constructors are called using the new keyword
  • Constructor execution flow:
    ----------------1. Immediately create a new object, as soon as new appears, it will open up space in the heap memory
    ---------- ------2. Set the newly created object as this in the function (important) (this==new object)
    ----------------3. Execute the function line by line The code
    ---------------- 4. Return the new object as the return value
  • Using an object created by a constructor, we become a class of objects, and a constructor becomes a class
    -------------------- Objects created by a constructor become instances of this class, Or an instance of this constructor
    insert image description hereinsert image description here
    insert image description here
    uses the constructor to create an object
    insert image description here
    instanceof function
    insert image description here
    insert image description here

Guess you like

Origin blog.csdn.net/weixin_40929263/article/details/108033077