对象继承的四种方式

1.传统的继承方式-原型链形式:缺点:过多的继承了没有用的属性 比如Father工厂里面创建的name

		Father.prototype.lastName = "teng";
		function Father(){
			this.name = "anchao"
		}
		var father = new Father();
		Son.prototype =father;
		function Son(){

		}
		var son = new Son();

2.借用构造函数来继承,使用call和apply改变this指向,借用别人的工厂创建了自己的对象。缺点:不能继承别人工厂的原型 比如访问student.address = undefined;

		Person.prototype.address = "地球";
		function Person(name,sex,age){
			this.name = name;
			this.sex = sex;
			this.age = age;
			this.sing = function(){
				console.log("I am"+this.name);
			}
		}
		function Student(name,sex,age,className){
			Person.call(this,name,sex,age);
			this.className = className;
		}

		var student = new Student("tenganchao","male",26,"三年五班");

3.共享原型来继承。缺点:不能更改儿子的原型,否则父亲的原型也跟着变化

		Father2.prototype.lastName = "teng";
		function Father2(){
			this.name = "anchao"
		}
		function Son2(){

		}
		function inherit(Target,Origin){
			Target.prototype = Origin.prototype
		}
		inherit(Son2,Father2);

		var son2 = new Son2();

4.圣杯模式。在共享原型的基础上,通过一个function F(){} 来改掉共享原型上的缺点,这样即能达到继承效果,又可以在自己原型链上进行更改

	Father3.prototype.lastName = "teng";

		function Father3(){

		}
		function Son3(){

		}
		function inherit3(Target,Origin){
			function F(){};
			F.prototype = Origin.prototype;//将原构(父)造函数与F构造函数共享一个原型
			Target.prototype = new F();//将目标(子)构造函数的原型指向了通过new F()创建的对象
			Target.prototype.constuctor = Target;//将constructor复原
			Target.prototype.uber = Origin.prototype;//查找继承的超类
		}
		inherit3(Son3,Father3);

		var son3 = new Son3();
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值