继承的多种方式

方法一:call()方法

		function Father (name, age) {
			// this指向父构造函数的对象实例
			this.name = name
			this.age = age
			this.money = function () {
				console.log('挣了1000元')
			}
		}
		function Son (name, age) {
			// this指向子构造函数的对象实例
			Father.call(this, name, age)
			this.exam = function () {
				console('考试')   //新增方法
			}
		}
		var son = new Son('小明', 12)
		console.log(son.name)   //小明
		console.log(son.age)    //12
		son.money()             //挣了1000元

方法二:通过原型链的方法

        function Father () {
		}
		Father.prototype.hello = 'hello'
		Father.prototype.money = function () {
			console.log('挣了1000元')
		}
		function Son () {
		}
		Son.prototype = new Father() //将Father中所有通过prototype添加的属性和方法都追加到Son上面,进而实现继承
		
		var son = new Son()
		console.log(son.hello)  //hello
		son.money()   //挣了1000元

方法三:通过 apply()方法

function Father (name, age) {
			this.name = name
			this.money = function () {
				console.log('挣了1000元')
			}
		}
		function Son (name,age) {
			Father.call(this, [name, age])
			this.exam = function () {
				console('考试')  //新增方法
			}
		}
		var son = new Son('小明',12)
		son.money()   //挣了1000元

方法四:混合原型链和 call()方法

		function Father (name, age) {
			this.name = name
			this.age = age
		}
		Father.prototype.money = function () {
			console.log('挣了1000元')
		}
		function Son (name, age) {
			Father.call(this, name, age)
		}
		Son.prototype = new Father()

		var son = new Son('小明', 12)
		console.log(son.name)  //小明
		son.money()           //挣了1000元

ES6中的继承

  		class Father {
			constructor (x, y) {
				this.x = x
				this.y = y
			}
			sum () {
				console.log(this.x + this.y)
			}
		}
		class Son extends Father {
			constructor (x, y) {
				super(x, y)
				this.x = x
				this.y = y
			}
			subtract () {
				console.log(this.x - this.y) //新增方法
			}
		}
		var son = new Son(3,4)
		son.sum()      //7
		son.subtract()    //-1
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值