js super detailed constructor


There is no difference between the creation method and ordinary functions, the difference is that the first letter of the constructor is used to capitalize

1. Definition (It is recommended to directly look at the code below)

/**
			 * 创建一个构造函数,
			 * 专门用来创建Person对象的
			 * 构造函数就是一个普通的函数,
			 * 创建方式和普通函数没有区别,
			 * 不同的是构造函数习惯上首字母大写
			 * */

See the following example:

			function Person(){
    
    	 

			 }
			 var per = new Person();
			 console.log(per);

2. Execution process and alias

/**
			  * 构造函数的执行流程:
			  * 1.立刻创建一个新的对象
			  * 2.将新建的对象设置为函数中this,在构造函数中可以使用this来引用新建的对象
			  * 3.逐行执行函数中的代码
			  * 4.将新建的对象作为返回值返回
			  * */
/**
			   * 使用同一个构造函数创建的对象,
			   * 我们称为一类对象,也将一个构造函数称为一
			   * 类。我们将通过一个构造函数创建的对象,
			   * 称为是该类的实例

			   * */

The objects created using the same constructor are called first-class objects,Also call a constructor a classWe will use a constructor to create an object called an instance of this class

3. Examples

3.1 "Making people"

			//创建一个人的构造函数
			  function Person(name, age, gender){
    
    
				  this.name = name;
				  this.age = age;
				  this.gender = gender;
				  this.sayname = function(){
    
    
					  alert(this.name);
				  }
			  }
			  var per = new Person("大黄", 18, "男");
			  //加了new 就当构造函数去调,不加new 调用的就是普通函数。
			  console.log(per);

3.2 "Making Dogs"

//创建狗的构造函数
			  function Dog(){
    
    
				  
			  }
			  var dog = new Dog();
			  console.log(dog);
			  
			  /**
			   * 
			   * this的情况:
					1.当以函数的形式调用时,this是window
					2.当以方法的形式调用时,谁调用方法this就是谁
					3.当以构造函数的形式调用时,this就是新创建的那个对象

			   * */

//Use instanceof to check whether an object is an instance of a class
//Syntax: object instanceof constructor

4. Disadvantages:


		<script type="text/javascript">
			function Person(name, age, gender){
    
    
							  this.name = name;
							  this.age = age;
							  this.gender = gender;
							  this.sayname = function(){
    
    
								  alert(this.name);
							  }
			}
			var per = new Person("大黄", 18, "男");
			var per2 = new Person("大宽", 19, "男");
			per.sayname();
			per2.sayname();
			
			//如果调10000次就会创建10000个,而且代码还一样,浪费资源
			console.log(per.sayname==per2.sayname);
			//这两个对象还不一样
		</script>

Improve

Write the function outside

<script type="text/javascript">
			function fun(){
    
    
			alert(this.name);
			}
			function Person(name, age, gender){
    
    
							  this.name = name;
							  this.age = age;
							  this.gender = gender;
							  this.sayname = fun
			}
			var per = new Person("大黄", 18, "男");
			var per2 = new Person("大宽", 19, "男");
			per.sayname();
			per2.sayname();
			
			//如果调10000次就会创建10000个,而且代码还一样,浪费资源
			console.log(per.sayname()==per2.sayname());
		</script>

Guess you like

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