(基础点复习一)js继承的几种方式

1.构造函数继承
利用call,apply,bind等方法,在构造函数内部改变this指向,调用别的构造函数

//构造函数继承
			//原型链上的方法和属性无法继承(无法复用)
			// function Person(){
			// 	this.name="person",
			// 	this.say=function(){
			// 		console.log('say');
			// 	}
			// }
			// Person.prototype.run=function(){
			// 	console.log('run');
			// }
			// function Student(){
			// 	Person.call(this);
			// 	this.age=19;
			// }
			// let s1=new Student();
			// console.log(s1);

2.原型链继承
父类实例作为子类原型

//原型链继承
			//实例化原型对象的属性是引入类型的时候,会出现浅拷贝问题,不能灵活的传值
			// function Person(){
			// 	this.name="person",
			// 	this.arr=[1,2];
			// 	this.say=function(){
			// 		console.log('say');
			// 	}
			// }
			// Person.prototype.run=function(){
			// 	console.log('run');
			// }
			// function Student(){
				
			// 	this.age=19;
			// }
			// Student.prototype = new Person();
			// let s1=new Student();
			// s1.arr.push(3);
			// let s2=new Student();
			// console.log(s1.arr);
			// console.log(s2.arr);

3.组合继承

//组合式继承(构造函数和原型链继承的结合)
			//Student.prototype = new Person();执行一次Person函数
			//通过实例化对象中Person.call(this)又执行一次Person()
			// function Person(){
			// 	this.name="person",
			// 	this.arr=[1,2];
			// 	this.say=function(){
			// 		console.log('say');
			// 	}
			// }
			// Person.prototype.run=function(){
			// 	console.log('run');
			// }
			// function Student(){
			// 	Person.call(this);
			// 	this.age=19;
			// }
			// Student.prototype = new Person();
			// let s1=new Student();
			// s1.arr.push(3);
			// let s2=new Student();
			// console.log(s1.arr);
			// console.log(s2.arr);
			
			//组合继承的优化
			function Person(){
				this.name="person",
				this.arr=[1,2];
				this.say=function(){
					console.log('say');
				}
			}
			Person.prototype.run=function(){
				console.log('run');
			}
			function Student(){
				Person.call(this);
				this.age=19;
			}
			// Student.prototype = Person.prototype;//两个的原型对象指向一个,一个修改另一个也修改
			// Student.prototype.constructor =Student;
			// Person.prototype.constructor = Person;
			Student.prototype = Object.create(Person.prototype);
			//new Object()通过构造函数来创建对象
			//Object.create()// es6创建对象的另一种方式,可以理解为继承一个对象, 添加的属性是在原型下。
			 Student.prototype.constructor =Student;
			let s1=new Student();
			s1.arr.push(3);
			let s2=new Student();
			console.log(s1);
			let p =new Person();
			console.log(p);
			
			
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值