js 实现继承

2021-07-09 00:05

阅读:430

标签:继承   cti   arguments   style   利用   type   部分   prot   on()   

我们现在要做的一件事情是像其他语言的面向对象一下实现继承多态

具体要求如下:

一个 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 实现继承

标签:继承   cti   arguments   style   利用   type   部分   prot   on()   

原文地址:http://www.cnblogs.com/sowhite/p/7095994.html


评论


亲,登录后才可以留言!