Comparison of advantages and disadvantages of js object creation methods, and advantages and disadvantages of js object Creation
Several Methods for comparing object creation in js
1. Factory Model
function createObj(name, sex){ var obj = new Object(); obj.name = name; obj.sex = sex; obj.sayName = function(){ alert(this.name); } return obj; }var person = createObj('Tom', 'man');
Disadvantages: ① The Object type cannot be determined (because all objects ).
② The created objects are not associated.
2. Constructor
function createObj(name, sex){ this.name = name; this.sex = sex; this.sayName = function(){ alert(this.name); } } var person = new createObj('Tom', 'man');
Disadvantages: ① multiple instances are created repeatedly and cannot be shared.
② Multiple instances have the sayName method, but they are not instances of the same Function.
3. Prototype Method
function createObj(){} createObj.prototype.name = 'Tom'; createObj.prototype.sex = 'man'; createObj.prototype.sayName = function(){ alert(this.name); }var person = new createObj();
Disadvantages: ① parameters cannot be passed in, and attribute values cannot be initialized.
② If the value of one instance is changed when the value of the reference type is included, it will be reflected in all instances.
4. Recommended combination (constructor + prototype)
function createObj(name, sex){ this.name = name; this.sex = sex; } createObj.prototype.sayName = function(){ alert(this.name); } var person = new createObj('Tom', 'man');
Advantage: constructor shares instance attributes, prototype sharing methods, and attributes to be shared. You can pass parameters to initialize attribute values.
5. Dynamic Prototype Method
function createObj(name, sex){ this.name = name; this.sex = sex; if(typeof this.sayName != 'function'){ createObj.prototype.sayName = function(){ alert(this.name); } } } var person = new createObj('Tom', 'man');
NOTE: if statements can only be called once, that is, they are executed when the method of the first instance is called. This method will be shared by all instances thereafter. In the dynamic prototype method, the prototype cannot be rewritten using the object literal.
The above is all the content of this article. I hope it will be helpful for your learning and support for helping customers.