当前位置: 代码迷 >> JavaScript >> JavaScript OOP(3) - 关于Prototype
  详细解决方案

JavaScript OOP(3) - 关于Prototype

热度:93   发布时间:2012-09-19 13:43:54.0
JavaScript OOP(三) -- 关于Prototype

由于constructor.prototype指向的是一object实例,并且只实例化一次,所以可能出现数据共享问题。

?

<html>
	<head>
		<title>object test</title>
		<script language="javascript">
		<!--
		
		function Student(name, age) {
			this.name = name;
			this.age = age;
			this.sayHello = function() {
				alert("Hello, I am " + this.name);
			}
			this.toString = function() {
				return this.name + " : " + this.age;
			}
		}
		
		function CollegeStudent(major) {
	  	this.major = major;
	  	this.toString = function() {
	  		return this.student.name + " : " + this.student.age + " : " + this.major;
	  	}
	  }
	  var studentPrototype = new Student("siyuan", 24);
	  CollegeStudent.prototype.student = studentPrototype;
  	
  	function testPrototype() {
  		var colleger1 = new CollegeStudent("software");
  		alert(colleger1);
  		var colleger2 = new CollegeStudent("hardware");
  		alert(colleger2);
  		colleger1.student.name = "siyuan1";
  		alert("modify colleger1.student.name");
  		alert(colleger1);
  		alert(colleger2);
  	}
		-->
		</script>
	</head>
	<body>
		<input type="button" value="test prototype" onclick="javascript:testPrototype();"/><br>
	</body>
</html>

?

  相关解决方案