js對象的創建和繼承

js對象的創建和繼承


1、對象的創建

創建對象的設計模式有很多種,這裏採用動態原型模式,是最優的方案。

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head>
	<meta http-equiv="Content-Type" content="text/html;charset=UTF-8">
	<title>Document</title>
</head>
<body>
	<script type="text/javascript">
		function Person (name,age,job) {
			// 屬性
			this.name = name;
			this.age = age;
			this.job = job;
			this.arr = ["hehe","hh"];

			//方法
			if(typeof this.sayName != "function"){
				Person.prototype.sayName = function(){
					alert(this.name);
				};
			}
		}

		var friend = new Person("Nicholas",29,"Soft Engineer");
		friend.arr.push("ee");
		alert(friend.arr);
		var friend1 = new Person("mike",20,"ss");
		alert(friend1.arr);
	</script>
</body>
</html>

2、對象的繼承

關於對象繼承的設計模式有很多種,這裏採用寄生組合式繼承,是最優的方案。

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head>
	<meta http-equiv="Content-Type" content="text/html;charset=UTF-8">
	<title>Document</title>
</head>
<body>
	<script type="text/javascript">
		function object(o){
			function F(){}
			F.prototype = o;
			return new F();
		}

		function inheritPrototype (subType,superType) {
			var prototype = object(superType.prototype);
			prototype.constructor = subType;
			subType.prototype = prototype;
		}

		function SuperType(name){
			this.name = name;
			this.colors = ["red","blue","green"];
		}

		SuperType.prototype.sayName = function(){
			alert(this.name);
		};

		function SubType(name,age){
			SuperType.call(this,name);
			this.age = age;
		}
		inheritPrototype(SubType,SuperType);
		SubType.prototype.sayAge = function(){
			alert(this.age);
		};
		var subType1 = new SubType("mary",20);
		var superType1 = new SuperType("aa",22);
		subType1.colors.push("element");
		superType1.colors.push("hhe");
		subType1.sayAge();
		subType1.sayName();

		console.log(subType1 instanceof SubType);
		console.log(subType1 instanceof SuperType);
		console.log(subType1.colors);
		console.log(superType1.colors);
		console.log(subType1.constructor == superType1.constructor);	
	</script>
</body>
</html>



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章