javascript Talk about the factory model "creating people"

1. Not much nonsense, code

			var obj = {
    
    
				name:"林徽因",
				age:19,
				sayname:function(){
    
    
					console.log(this.name);
			};
			var obj2 = {
    
    
				name:"林青霞",
				age:18,
				sayname:function(){
    
    
					console.log(this.name);
			};
			var obj3 = {
    
    
				name:"马钰",
				age:20,
				sayname:function(){
    
    
					console.log(this.name);

The above writing is particularly troublesome.
Using the factory model is relatively simple.

2. Factory mode: above code

Pay attention to observation, the two species created below have a very critical code

var obj = new Object();

2.1 First, we come to "creatPerson()"

		function creatPerson(name, age){
    
    
				function creatPerson(name, age){
    
    
				var obj = new Object();
				obj.name = name;
				obj.age = age;
				obj.sayname = function(){
    
    
					alert(this.name);
				};
				return obj;
			}
			var jb1 = creatPerson("林青霞",18);
			console.log(jb1);
			jb1.sayname();
			//造狗呢?来,上代码!
			function creatDog(name, age){
    
    
				var obj = new Object();
				obj.name = name;
				obj.age = age;
				obj.sayname = function(){
    
    
					alert("呱呱~~~~");
				};
				return obj;
			}
			var jb2 = creatDog("大黄",45);
			console.log(jb2);
			jb2.sayname();
				obj.name = name;
				obj.age = age;
				obj.sayname = function(){
    
    
					alert(this.name);
				};
				return obj;
			}
			var jb1 = creatPerson("林青霞",18);
			console.log(jb1);
			jb1.sayname();
			

2.2 "Fuck", soon, it's finished, how about making other species, creatDog() makes dogs


			//造狗呢?来,上代码!
			function creatDog(name, age){
    
    
				var obj = new Object();
				obj.name = name;
				obj.age = age;
				obj.sayname = function(){
    
    
					alert("呱呱~~~~");
				};
				return obj;
			}
			var jb2 = creatDog("大黄",45);
			console.log(jb2);
			jb2.sayname();

3. Factory model: disadvantages

The object created by the factory method, the constructor used is Object, so the objects created are all of the Object type, which makes it impossible for us to distinguish a variety of different types of objects

Disadvantage picture
In the next lecture, let’s talk about avoiding this shortcoming

Guess you like

Origin blog.csdn.net/weixin_44154094/article/details/112202178