js继承方法与类上的数据类型

这篇博客深入探讨了JavaScript中实现继承的几种方式,包括构造函数式继承、原型链继承、组合继承以及寄生式组合继承。通过示例代码,详细解释了每种方式的工作原理和优缺点,特别是如何在子类中复用父类的构造函数和原型数据。同时,文中提到了静态数据的定义和访问方式,并展示了实例对象无法直接访问静态数据的特性。
摘要由CSDN通过智能技术生成
<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<meta name="viewport" content="width=device-width, initial-scale=1.0">
	<title>Document</title>
</head>
<body>
	<script type="text/javascript">
		/**
		 * 类上有三种数据类型
		 *1.实例数据(构造函数中的this.data = data)
		 *2.原型数据 构造函数原型上的数据
		 *3.静态数据 构造函数自身的数据
		 *   (构造函数创建出来的对象无法访问)
		 */
	
	//父类
		function Animals(type, name) {
			//实例数据
			this.type = type;
			this.name = name; 
		}
		//原型数据
		Animals.prototype.getInfo = function() {
			// body...
			console.log(this.type, this.name);
		};

	//子类
		function Dog(type, name)  {
			//复用父类的构造函数,继承实例数据(构造函数式继承)
			Animals.call(this, type, name);
			//可以新增或改写
			this.type = 'Dog';
			this.price = 10;
		}
	/*构造函数式组合继承父类的原型(构造函数式继承实例数据,直接继承实例数据)组合
		Dog.prototype = Animals.prototype;
		Dog.prototype.constructor = Dog;
	*/

	/*类式组合继承父类(构造函数式继承实例数据+原型链继承原型数据)组合
		Dog.prototype = new Animals();(原型链继承)
		Dog.prototype.constructor = Dog;
	*/

	//寄生式组合继承父类(构造函数式继承实例数据+寄生式继承原型数据)组合
		function inherit(child, father) {
			function F() {
				this.constructor = child;
			}
			F.prototype = father.prototype;
			child.prototype = new F();
			//可以省略return child;
		}
		
		inherit(Dog, Animals);
		//静态数据
		Dog.number = 10;

		//创建实例对象那个
		var dog1 = new Dog('dog', 'litle');
		console.log(dog1);
		dog1.getInfo();
		//实例对象无法访问Dog.number静态数据
		//console.log(dog1.number);
		//必须Dog.number进行访问
		console.log(Dog.number);
		
	</script>
</body>
</html>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值