Home >Web Front-end >JS Tutorial >Detailed explanation of JavaScript parasitic constructor pattern and safe constructor pattern examples
Parasitic Constructor Mode
Generally, when none of the previous modes are applicable, the parasitic constructor mode can be used. The basic idea of this pattern is to create a function that simply encapsulates the code that creates the object and then returns the newly created object; but on the surface, this function looks like a typical constructor. Below is an example.
function Person(name, age, job){ var o = new Object(); o.name = name; o.age = age; o.job = job; o.sayName = function(){ alert(this.name); }; return o; } var friend = new Person("Nicholas", 29, "Software Engineer"); friend.sayName(); //"Nicholas"
In this example, the Person function creates a new object, initializes the object with the corresponding properties and methods, and then returns the object. This pattern is exactly the same as the factory pattern, except that the new operator is used and the wrapper function used is called a constructor. If the constructor does not return a value, it will return a new object instance by default.
Safe constructor pattern
The so-called safe object refers to an object that has no public properties and whose methods do not reference this. Stable objects are best used in some safe environments (where the use of this and new are prohibited), or to prevent data from being modified by other applications (such as mashup programs). Safe constructors follow a similar pattern to parasitic constructors, but there are two differences: first, the instance method of the newly created object does not reference this; second, the constructor is not called using the new operator. According to the requirements of a stable constructor, the previous Person constructor can be rewritten as follows.
function Person(name, age, job){ //创建要返回的对象 var o = new Object(); //可以在这里定义私有变量和函数 //添加方法 o.sayName = function(){ alert(name); }; //返回对象 return o; }
The above is the detailed content of Detailed explanation of JavaScript parasitic constructor pattern and safe constructor pattern examples. For more information, please follow other related articles on the PHP Chinese website!