js 原型 2019-12-15

2019-12-15  本文已影响0人  Hi丶粢醍

原型:constructor

<script>
    function Star(uname, age) {
        this.uname = uname;
        this.age = age;
    }
    // 很多情况下,我们需要手动的利用constructor 这个属性指回 原来的构造函数
    // Star.prototype.sing = function() {
    //     console.log('我会唱歌');
    // };
    // Star.prototype.movie = function() {
    //     console.log('我会演电影');
    // }
    Star.prototype = {
        // 如果我们修改了原来的原型对象,给原型对象赋值的是一个对象,则必须手动的利用constructor指回原来的构造函数
        constructor: Star,
        sing: function() {
            console.log('我会唱歌');
        },
        movie: function() {
            console.log('我会演电影');
        }
    }
    var ldh = new Star('刘德华', 18);
    var zxy = new Star('张学友', 19);
    console.log(Star.prototype);
    console.log(ldh.__proto__);
    console.log(Star.prototype.constructor);
    console.log(ldh.__proto__.constructor);
</script>

构造函数、实例、原型对象三者之间的关系

构造函数、实例、原型对象三者之间的关系

原型链

原型链

原型对象中的this指向

    原型对象函数里面的this 指向的是 实例对象

扩展内置对象

扩展内置对象

继承 call()

<script>
    // call 方法
    function fn(x, y) {
        console.log('我想喝手磨咖啡');
        console.log(this);
        console.log(x + y);


    }
    var o = {
        name: 'andy'
    };
    // fn();
    // 1. call() 可以调用函数
    // fn.call();
    // 2. call() 可以改变这个函数的this指向 此时这个函数的this 就指向了o这个对象
    fn.call(o, 1, 2);
</script>

借用父构造函数继承属性

<script>
    // 1. 父构造函数
    function Father(uname, age) {
        // this 指向父构造函数的对象实例
        this.uname = uname;
        this.age = age;
    }
    // 2 .子构造函数 
    function Son(uname, age, score) {
        // this 指向子构造函数的对象实例
        Father.call(this, uname, age);
        this.score = score;
    }
    var son = new Son('刘德华', 18, 100);
    console.log(son);
</script>

借用父构造函数继承属性

<script>

    // 1. 父构造函数
    function Father(uname, age) {
        // this 指向父构造函数的对象实例
        this.uname = uname;
        this.age = age;
    }
    Father.prototype.money = function() {
        console.log(100000);

    };
    // 2 .子构造函数 
    function Son(uname, age, score) {
        // this 指向子构造函数的对象实例
        Father.call(this, uname, age);
        this.score = score;
    }
    // Son.prototype = Father.prototype;  这样直接赋值会有问题,如果修改了子原型对象,父原型对象也会跟着一起变化
    Son.prototype = new Father();
    // 如果利用对象的形式修改了原型对象,别忘了利用constructor 指回原来的构造函数
    Son.prototype.constructor = Son;
    // 这个是子构造函数专门的方法
    Son.prototype.exam = function() {
        console.log('孩子要考试');

    }
    var son = new Son('刘德华', 18, 100);
    console.log(son);
    console.log(Father.prototype);
    console.log(Son.prototype.constructor);
</script>
上一篇 下一篇

猜你喜欢

热点阅读