我们现在要做的一件事情是像其他语言的面向对象一下实现继承多态
具体要求如下:
一个 Father 构造函数,一个 Child 构造函数,其中改写 Father中的部分参数, new Child() 表示出一个新的child
var Father = function (name) { this.name = name this.say = function () { console.log('i am ' + name) } } var Child = function (name,age) { this.age = age; this.say = function () { console.log("name:" + this.name + " and age:" + this.age); } } Child.prototype = new Father() var he = new Child('asd',12)
console.log(he.firstName) // qiao
console.log(he.name)
console.log(he.age)
he.say()
无法输出 name 是因为不能穿参数
var Father = function (name) { this.name = name this.firstName = 'qiao' this.say = function () { console.log('i am ' + name) } } var Child = function (name,age) { this.tempMethod = Father this.tempMethod(name) this.age = age; this.say = function () { console.log("name:" + this.name + " and age:" + this.age); } } var he = new Child('asd',12) console.log(he.firstName) // qiao console.log(he.name) // sad console.log(he.age) // 12 he.say() // name:undefined and age:12
这样书写就可以继承name了
利用call可以这样书写
var Child = function (name,age) { Father.call(this,name) this.age = age this.say = function(){ console.log('i am ' + name +'and age '+ age ) } }
利用apply的话会更加巧妙一点,不用管参数是什么
var Child = function (name,age) { Father.apply(this,arguments) this.age = age this.say = function(){ console.log('i am ' + name +'and age '+ age ) } }
但是这样写虽然实现了继承,但是却没有利用原型进行继承,所以只是一种表面上的继承,实际上并没有原型上的联系,下面是如何利用原型进行继承
var Iphone = function () { this.price = 4000 } var IphoneX = function () { this.say = function(){ console.log('i am more expensive'); } } IphoneX.prototype = Iphone.prototype; var a = new IphoneX()
现在最新出的js class可以很优雅的实现这个
class Iphone { constructor() { this.price = 4000 } } class IphoneX extends Iphone { say() { console.log('expensive'); } } var a = new IphoneX(); a.say() console.log(a.price)