这篇文章会让你对原型焕然一新

75 阅读1分钟

开启掘金成长之旅!这是我参与「掘金日新计划 · 12 月更文挑战」的第32天,点击查看活动详情

prototype

 function Handphone() {

    }
    //prototype
    console.log(Handphone.prototype)

原型prototype其实是function对象的一个属性

image.png

我们通过prototype去绑定属性,看看能否访问到

function Handphone(color, brand) {
        this.color = color;
        this.brand = brand;
        this.screen = '18.9';
        this.system = 'Android';
    }
    //prototype绑定属性
    Handphone.prototype.rom = '64G';
    Handphone.prototype.ram = '6G';

    var hp1 = new Handphone('red', '小米');
    var hp2 = new Handphone('black', '华为');

    console.log(hp1.rom)
    console.log(hp2.ram)
  • 这个prototype是定义构造函数构造出的每个对象的公共祖先
  • 所有被该构造函数构造出的对象都可以继承原型上的属性和方法

image.png

访问的时候,当this上定义的话,就不会在访问在原型上重新定义的属性

  function Handphone(color, brand) {
        this.color = color;
        this.brand = brand;
        this.screen = '18.9';
        this.system = 'Android';
    }
    Handphone.prototype.rom = '64G';
    Handphone.prototype.ram = '6G';
    Handphone.prototype.screen = '16:9';

    var hp1 = new Handphone('red', '小米');
    var hp2 = new Handphone('black', '华为');

    console.log(hp1.screen)
    console.log(hp2.screen)

我们通过prototype定义了screen为 16.9,输出结果居然是 18.9

image.png

原型的作用

我们在实例化对象增加属性时通过prototype访问

     function Test() {

    }
    Test.prototype.name = 'prototype';
    var test = new Test();

    test.num = 1;
    console.log(Test.prototype)

输出是没有看到结果了,他这个num是放到this上面,这样增加是不行的

image.png

delete 也不可行

  function Test() {

    }
    Test.prototype.name = 'prototype';
    var test = new Test();

    delete test.name;
    console.log(Test.prototype)

3160081379da538e6ca56e67c78a9d5.png

通过实例化对象来进行增,删,改自己的祖先是不可行的

    function Handphone(color, brand, system) {
        this.color = color;
        this.brand = brand;
        this.system = system;
    }

    console.log(Handphone.prototype)

输出一个constructor,我们只需知道constructor对应的是构造函数本身 483b5c846e8d0715b6f406cd7cdfa5e.png