菜鸟笔记:js的多种继承方法

			//原型链继承:原型链上都是实例
			//所有子类实例共享父类引用类型属性,动一个影响所有、不可传参
			function Parent () {
				this.name = "zxx";
			}
			
			Parent.prototype.getName = function () {
				return this.name
			}
			
			function Child () { }
				//将子类的原型指向父类实例
			Child.prototype = new Parent();
			
			var child = new Child();
			
			console.log(child.getName())
			console.log(child.name)
			
			//借用构造函数使用实现继承&&组合继承
			//经典继承
			function Parent () {
				this.name = "zx"
			}
			
			function Child () {
				Parent.call(this)
			}
			
			//==================
			function Parent1 (name) {
				this.name = name
			}
			
			Parent1.prototype.getName1 = function () {
				return this.name
			}
			Parent1.prototype.sex = "man"
			
			function Child1 (name,age) {
				this.age = age;
				Parent1.call(this,name);
			}
			
			Child1.prototype = new Parent1()
			
			var child1 = new Child1("wd", 23)
			console.log(child1.age)
			console.log(child1.getName1())
			//原型式继承:传入一个对象,以其作为原型返回一个对象
			function creatObj(obj) {
				function F() {};
				F.prototype = obj;
				return new F();
			}
			
			var person = {
				name: "zx",
				gf: ["qw","er"]
			}
			var son1 = creatObj(person)
			var son2 = creatObj(person)
			//引用型属性会被共享
			son1.gf.push("zx")
			console.log(son2.gf)

			//寄生组合继承:最理想的继承
			//解决了组合继承需要两次调用构造函数的问题,避免了属性冗余的问题
			function Parent2 (name) {
				this.name = name;
				this.nums = [1,2,3,4,4]
			}
			
			Parent2.prototype.sex = "women"
			
			function Child2 (name,age) {
				this.age = age
				Parent2.call(this,name)
			}
			  //这里非常巧妙的用了一个空白的构造函数 F 替代了一次Parent的调用
			  //避免了child3和Child2.prototy的引用属性冗余
			var F = function () { }
				
			F.prototype = Parent2.prototype
			var f1=new F()
			Child2.prototype = f1
			
			var child2 = new Child2("asclin",12)
			console.log(child2.sex)
			
			
			
			//封装寄生构造继承
			//1.传入父类,返回继承了父类原型属性,但没有任何自身属性的对象
			function getBlankObj (obj) {
				var F = function (){};
				F.prototype = obj.prototype;
				return new F();
			}
			//2.设置子类型的原型为返回的对象
			function prototype(son, father) {
				son.prototype = getBlankObj(father);
			}
			
			
			function Parent3 (name) {
				this.name = name;
				this.nums = [1,2,3,4,4]
			}
			
			Parent3.prototype.sex = "women"
			
			function Child3 (name,age) {
				this.age = age
				Parent3.call(this,name)
			}

			//3.调用方法,先获得祖父辈以上的属性,新建实例对象时再去获取爹的属性
			prototype(Child3,Parent3);
			var child3 = new Child3("c3",15)
			console.log(child3.sex)
			

原地址链接

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值