一段js的思考

 写了很久JS,还以为这段代码可以正常输出,谁知道输出超乎我的形象:

<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<title></title>
		<script type="text/javascript">
			function MSG(a,b,c,d){
				this.a=a;
				this.b=b;
				this.c=c;
				this.d=d;
				this.e="喜欢";
				var that=this;   //方便私有函数haha()访问
				this.say=function(){
					console.log(haha());
				}
				this.ca=function(){
					return that.c+this.e+this.d;
				}
				function haha(){
					return this.a+",今年"+this.b+"岁;";
				//	return this.a+",今年"+this.b+"岁;"+this.ca();
				//	return that.a+",今年"+that.b+"岁;"+that.ca();
				}
			}
			var my=new MSG('张三','25','男','美女');
			my.say();
		</script>
	</head>
	<body>
	</body>
</html>

  

以下这段代码居然报错,呜呜呜呜呜。。。。。。。

<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<title></title>
		<script type="text/javascript">
			function MSG(a,b,c,d){
				this.a=a;
				this.b=b;
				this.c=c;
				this.d=d;
				this.e="喜欢";
				var that=this;   //方便私有函数haha()访问
				this.say=function(){
					console.log(haha());
				}
				this.ca=function(){
					return that.c+this.e+this.d;
				}
				function haha(){
				//	return this.a+",今年"+this.b+"岁;";
				 	return this.a+",今年"+this.b+"岁;"+this.ca();
				//	return that.a+",今年"+that.b+"岁;"+that.ca();
				}
			}
			var my=new MSG('张三','25','男','美女');
			my.say();
		</script>
	</head>
	<body>
	</body>
</html>

  

修改以上的代码,让that=this;此时that和this指向同一位置,就可以啦。。。

<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<title></title>
		<script type="text/javascript">
			function MSG(a,b,c,d){
				this.a=a;
				this.b=b;
				this.c=c;
				this.d=d;
				this.e="喜欢";
				var that=this;   //方便私有函数haha()访问
				this.say=function(){
					console.log(haha());
				}
				this.ca=function(){
					return that.c+this.e+this.d;   //this==that
				}
				function haha(){
				//	return this.a+",今年"+this.b+"岁;";
				// 	return this.a+",今年"+this.b+"岁;"+this.ca();
					return that.a+",今年"+that.b+"岁;"+that.ca();
				}
			}
			var my=new MSG('张三','25','男','美女');
			my.say();
		</script>
	</head>
	<body>
	</body>
</html>

  

总结:

私有变量】 在对象内部使用'var'关键字来声明,而且它只能被私有函数和特权方法访问。 
【私有方法】 在对象的构造函数里声明(或者是通过varfunctionName=function(){...}来定义),
它能被特权方法调用(包括对象的构造方法)和私有方法调用,私有函数只能访问私有的方法和属性。 
【特权方法】通过this.methodName=function(){...}来声明而且可能被对象外部的代码调用。
它可以使用:this.特权函数() 方式来调用特权函数,使用 :私有函数()方式来调用私有函数。

【公共属性】 通过this.variableName来定义而且在对象外部是可以读写的。不能被私有函数所调用。 
【公共方法】 通过ClassName.prototype.methodName=function(){...}来定义可以从对象外部来调用。 
【原型属性】 通过ClassName.prototype.propertyName=someValue 来定义。 
【静态属性】 通过ClassName.propertyName=someValue 来定义。
【静态方法】 通过ClassName.funName=function(){...} 来定义。

原文地址:https://www.cnblogs.com/libin-1/p/5877094.html