JavaScript实现伪继承的方式

下面通过代码展示在JavaScript中如何实现伪继承,

         <script type="text/javascript">
			
			function Person(name ,age){
				
				this.name = name;
				this.age = age;
				this.sayHello = function(){
				   console.log(this.name + "向您打招呼!");
				}
			}
			
			var per = new Person("牛魔王",22);
			per.sayHello();
			function Student(name ,age,grade){
				this.inherit_temp = Person;
				this.inherit_temp(name,age);
				this.grade = grade;
			}
			
			Student.prototype.intro = function(){
				console.log("%s是个学生,读%d年级" ,this.name ,this.grade);
			}
			
			var stu = new Student("孙悟空" ,34,5);
			console.log(stu instanceof Student);
			console.log(stu instanceof Person);
			stu.sayHello();
			stu.intro();
			
		</script>

结果:

                                                

上面说到的伪继承的关键在于子类构造器需要以this作为调用者来调用父类构造器,这样的父类构造器中的this 就会变成代表子类,子类就可以得到原父类定义的实例属性和方法,因此这种伪继承的方式完全可以使用apply或call来实现,只要在使用apply或call调用时指定this作为调用者即可。

         <script type="text/javascript">
			function Person(name ,age){
				
				this.name = name;
				this.age = age;
				this.sayHello = function(){
				   console.log(this.name + "向您打招呼!");
				}
			}
			
			var per = new Person("牛魔王",22);
			per.sayHello();
			function Student (name,age,grade){
				
				Person.call(this,name,age);
				//Person.apply(this,[name ,age]);
				this.grade = grade;
			}
			
			Student.prototype.intro = function(){
				console.log("%s是个学生,读%d年级" ,this.name ,this.grade);
			}
			
			var stu = new Student("孙悟空" ,34,5);
			console.log(stu instanceof Student);
			console.log(stu instanceof Person);
			stu.sayHello();
			stu.intro();
			
		</script>

结果:

                                                         

 

 

猜你喜欢

转载自blog.csdn.net/IBLiplus/article/details/81078846