阅读背景:

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()			// 直接调



你的当前访问异常,请进行认证后继续阅读剩余内容。

分享到: