JavaScript Design Patterns constructor mode

The constructor is used to create specific types of objects - not just declare the object using the constructor can accept parameters in order to create the first members of the value object object. We can customize your own configuration Anhui to study, and then inside the statement from property or method defined type object.

In JavaScript, the constructor is usually considered to achieve instance, JavaScript is no concept of class, but it is a special constructor. To call a custom constructor by new keyword within the constructor, this keyword refers to the object is newly created.

Role configuration mode:

  • For a particular type of object creation
  • The first time declared to the object assignment
  • Constructors own statement, given the properties and methods

application

For example, Zhang and Li are required to buy a small door for the new house, then we can use this process to buy the door constructor to achieve.

  

 But with the special needs of small Li pattern door, then the above method is not so useful anymore:

  

 Now it functions to achieve, but, once every implementation of a new subject, too waste of resources, so we can be simplified as follows:

<script>
        function BuyDoor(huawen){
            if(!(this instanceof BuyDoor)){
                return new BuyDoor();
            }
            var _huawen  = "普通";
            if(huawen){
                _huawen = huawen;
            };
            this.suo = "普通";
            this.huawen = _huawen;
            this.create = function(){
                return "锁头" + this.suo + ",花纹" + this.huawen
            }
        }
         var xiaozhang = new BuyDoor();
         console.log(xiaozhang.create());
         var xiaoli =BuyDoor('绚丽');
         console.log(xiaoli.create());
    </script>

Constructor mode Caution:

  • When the business logic processing function declaration
  • And to distinguish the difference between singleton cases implemented with a single initialization
  • Recommend constructor capitalized
  • Note that the cost of new

Guess you like

Origin www.cnblogs.com/yuyujuan/p/12128862.html