首页 > 代码库 > js 实现继承
js 实现继承
我们现在要做的一件事情是像其他语言的面向对象一下实现继承多态
具体要求如下:
一个 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 ) } }
js 实现继承
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。