前端菜鸟成长记(三)

2018-12-02  本文已影响0人  貓咪是大王
老规矩,我先放题目 稍后更新答案
 昨天和今天解决了构造函数,创建类和构造对象的问题。今天讨论一下继承和原型链的问题。
    思考:面向对象的语言会有 继承、封装、多态 等等特性。js是如何实现这些特性的?

    1,js有几种实现继承的方法(我直接给答案,原型链继承,借用构造函数继承,组合继承)?各自的优缺点是什么?<br><br><br>
   
    <pre>
        function Parents (name,age) {
            this.name = name;
            this.age = age;
            this.habits = 'sing'
        }
        Parents.prototype.say = function(){
            console.log('my name is ' + this.name + ', am ' 
            + this.age + ' years old, and i like ' + this.habits)
        }

        function Childs (name,age) {
            Parents.apply(this, arguments);
            this.habits = 'play computer game'
        }

        Childs.prototype = new Parents();

        var xiaoming = new Childs('xiaoming',7);
        
        xiaoming.say()  // 2,输出什么?

        Childs.prototype.say = function(){
            console.log('emmm, i dont want to talk')
        }

        xiaoming.say() // 3, 输出什么? 

        Childs.prototype.props = [1,2,3]

        var daming = new Childs('daming',12);

        xiaoming.props.push(4);

        console.log(daming.props)  // 4,

    </pre>

    5,上面的例子使用的是什么继承方法?<br><br><br>    

    6,在第二问处,为什么xiaoming并没有定义say方法却能正确的使用say方法?<br><br><br>
   
    7,在第三问处,为什么结果和第二问处不一样?<br><br><br>    
上一篇下一篇

猜你喜欢

热点阅读