JavaScript寄生组合继承

想讲个题外话,为什么我提到这个名字总能想到日本的一部电影《寄生兽》? exm?


			// 直接调用this指向window,用new不是
			function Father(name,age){
				this.name = name;
				this.age = age;
			}
			// 创建一个父类对象
			var f = new Father('ilv',22);
			
			Father.prototype.hi = function(){
				console.log("hello "+this.name,this.age);
			}
			Father.prototype.salary = 9999;
			f.hi();

			function Child(name,age,gender){
				Father.apply(this,arguments);
				this.gender = gender;
			}

			//var c = new Child('mmc',18,'M');
			//console.log(c.name,c.gender);
			// 构造器继承方法无法获取父类原型上的方法
			//c.hi(); //报错,没有这个方法


			// Object.create(arg);
			// 创建一个空对象,并且对象的原型指向参数
			// 思考为什么不能直接? Child.prototype = Father.prototype ?
			Child.prototype = Object.create(Father.prototype);
			Child.prototype.constructor = Child;
			var c = new Child('mmc',18,'M');
			c.hi(); /// 9999 
			console.log(c.salary);
			Child.prototype.hi = function(){
				console.log(this.name,this.age,this.gender);
			}
			// 重写父类方法
			c.hi();

			console.log(f.__proto__   === Father.prototype);  // true
			console.log(typeof Father.prototype.__proto__); // Object
			console.log(Child.prototype.__proto__ === Father.prototype); // true
			// 至此,原型链的含义也就出来了..

			console.log(c instanceof Father); //true
			console.log(new Object() instanceof Array); //false
			// 左边对象 右边函数(构造器)
			// 左边不是对象直接返回false
			//怎么判读? 右边的prototype属性是否出现在左边的对象的原型链上

			/*
				解释:直接Child.prototype = Father.prototype 。
				当我们给child prototype加些属性后,father也会加上
			*/
			
			// 并不是所得函数都有prototype对象属性:bind()


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值