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>



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值