JS构造函数:new关键字、及一些相关案例

161 阅读1分钟

构造函数:new关键字(任何对象都有构造函数)

定义:new关键字后面跟函数,是一个表达式(运算符),创建对象的运算,整个表达式一定会得到一个对象

//假设fn为一个函数的标记符 
  new fn//创建对象,然后调用函数,不传参==>new无参
  new fn()//创建对象,然后调用函数,并传参数==>new带参

new fn()的操作步骤如下:

1.创建一个空对象{}

2.运行构造函数,让内部的this指向创建的对象(用创建的空对象去调用构造函数)

3.整个表达式的结果看函数的返回值:
     1.返回值是引用数据,那么就是返回值(引用数据)
     2.返回值不是引用数据,那么返回值就是这个构造函数运行完毕之后的创建的那个对象。
     

image.png

image.png

new相关案例:

1.代码机相关解析:

 <script type="text/javascript">
		function fn(){
			var obj={say:function(){
				return obj;
			}}
			return obj;
		}
		var re=new fn();//re=obj={say:function(){return obj;}}
		var re2=fn().say;//re2=function(){return obj;}
		var re3=new re2();//re3=obj={say:function(){return obj;}}
		console.log(re);
                    console.log(re2);
                    console.log(re3);
                    
	</script>
            

答案:

image.png

2.代码及相关解析:

<script type="text/javascript">
		function fn(){
			this.name="karen";
			return function fm(){
				console.log("fm运行了");
				this.name="jack"
			}
		}
		var f1=new fn();//f1=function fm(){console.log("fm运行了");this.name="jack"}
		console.log(f1)
	</script>

答案:

image.png

3.代码及相关解析:

<script type="text/javascript">
		function fn(){
			this.name="marry";
			var obj={
				name:"karen",
				fm:function(){
					this.name="jack"
				}
			}
			return obj;
		}
		var f1=new fn();//f1=obj={name:"karen",fm:function(){this.name="jack"}}
		console.log(f1.name);//"karen"
		var f2=new ((new fn()).fm)();//f2=new (f1.fm)()=new fm()
		//f2={name:"jack"}
		console.log(f2.name);//"jack"
		var f3=new fn();//f3=obj={name:"karen",fm:function(){this.name="jack"}}
		var f4=new (f3.fm)();//f4=new fm()={name:"jack"}
		console.log(f3.name,f4.name)//"karen","jack"
		</script>

答案:

image.png

4.代码及相关解析:

<script type="text/javascript">
			function Parent(){
				this.a=1;
				this.b=[1,2,this.a];
				this.c={
					demo:5
				};
				this.show=function(){
					console.log(this.a,this.b,this.c.demo);
				}
				this.change=function(){
					this.a=this.b.length;
					this.c.demo=this.a++;
				}
				return "hello";
			}
			var parent=new Parent();
			/*
			parent={a:1,b:[1,2,1],c:{demo:5},
			show:function(){console.log(this.a,this.b,this.c.demo);},
			chang:function(){this.a=this.b.length;this.c.demo=this.a++;}}
			*/
			parent.change();//this=parent
			/*
			parent={a:3,b:[1,2,1],c:{demo:3},
			show:function(){console.log(this.a,this.b,this.c.demo);},
			chang:function(){this.a=this.b.length;this.c.demo=this.a++;}}
			*/
			parent.show();//打印的结果为:4,[1,2,1],3
                            //为什么a从3变成了4,因为chang中的a++;
		</script>

答案:

image.png