现在的位置: 首页 > 综合 > 正文

javascript读书笔记2—-使用原型进行扩展的一个需要注意的地方

2018年04月21日 ⁄ 综合 ⁄ 共 1127字 ⁄ 字号 评论关闭

在javascript中可以使用原型来达到继承的效果

如下代码

<script type="text/javascript">
	function People() {
		this.name = 'people';
	}
	function Student() {
	}
	People.prototype.fun1 = function(){
		alert('people fun')
	}
	Student.prototype.fun2 = function(){
		alert('student fun');
	}
	Student.prototype = new People();
	new Student().fun1();//people fun
	alert(new Student().name);//people
</script>

        为People扩展了一个fun1的函数, 为Student扩展了一个fun2的函数,这时如果需要Student来继承People的函数,

那么可以使用上面的方式来继承,Student的原型指向了一个Perople的实例,那么我们再Student中就能够使用

People中的函数和属性,这时通过new Student().name也是可以访问到People的属性的,如果不想让Student访问

到People的name属性,那么要使用如下方法:

<span style="white-space:pre">	</span><script type="text/javascript">
		function People() {
			this.name = 'people';
		}
		function Student() {
		}
		People.prototype.fun1 = function(){
			alert('people fun')
		}
		Student.prototype.fun2 = function(){
			alert('student fun');
		}
		Student.prototype = People.prototype;
		new Student().fun1();//people fun
		alert(new Student().name);//undefined
	</script>

这样就访问不到People中的name属性了, 因为name是属于People的一个实例的,在进行原型扩展的时候,name的

属性并不在原型链上按照Java的类和对象来理解呢,就是一个类的属性在在还没实例化的时候是不存在的,不能获取到

它值,所以上面Student指向People的实例的时候,name已经可以访问了

而第二种情况是因为在访问一个属性的时候,会沿着原型链向上查找这个属性,而在这里,People和Student的原型都

没有扩展name属性,所以自然为undefined











抱歉!评论已关闭.