The simple distinction between the factory model, the constructor model, and the prototype model for creating objects

Factory mode

  • Call Fun1 without the keyword new
  • You can take parameters when creating an object
  • Generate an object in Fun1 and return it
  • The parameter exists in obj1 itself
  • After the instantiated object changes the attribute value, it does not affect each other
  • It is equivalent to creating parameters in obj1 itself when instantiating, method
function Fun1(value1, value2, value3) {
    
    
	var _obj = new Object();
	_obj.value1 = value1;
	_obj.value2 = value2;
	_obj.value3 = value3;
	_obj.fun1 = function() {
    
    
		// this 指向 _obj
		console.log(this.value1);
	}
	return _obj;
}
var obj1 = Fun1("value1", "value2", "value3");

Constructor pattern

  • Call Fun2 with the keyword new
  • You can take parameters when creating an object
  • Fun2 hangs the data on its own this and does not return content
  • The parameter exists in obj2 itself
  • After the instantiated object changes the attribute value, it does not affect each other
  • It is equivalent to creating parameters in obj2 itself when instantiating, method
function Fun2(value1, value2, value3) {
    
    
	this.value1 = value1;
	this.value2 = value2;
	this.value3 = value3;
	this.fun1 = function() {
    
    
		// this 指向 Fun2
		console.log(this.value1);
	}
}
var obj2 = new Fun2("value1", "value2", "value3");

Prototype mode

  • Call Fun3 with the keyword new
  • Cannot take parameters when creating an object
  • Fun3 hangs the data on the prototype and does not return content
  • The parameter exists on the prototype chain of obj3 obj3.__proto__
  • After the instantiated object changes the attribute value, it affects each other
  • It is equivalent to inheriting parameters and methods when instantiating
function Fun3() {
    
    }
Fun3.prototype.value1 = "value1";
Fun3.prototype.value2 = "value2";
Fun3.prototype.value3 = "value3";
Fun3.prototype.fun1 = function() {
    
    
	// this 指向 Fun3
	console.log(this.value1);
};
var obj3 = new Fun3();

//end

Guess you like

Origin blog.csdn.net/u013970232/article/details/109516004