zoukankan      html  css  js  c++  java
  • 学生问的一道javascript面试题[来自腾讯]

     1     function Parent() {
     2             this.a = 1;
     3             this.b = [1, 2, this.a];
     4             this.c = { demo: 5 };
     5             this.show = function () {
     6                 console.log(this.a , this.b , this.c.demo );
     7             }
     8         }
     9         function Child() {
    10             this.a = 2;
    11             this.change = function () {
    12                 this.b.push(this.a);
    13                 this.a = this.b.length;
    14                 this.c.demo = this.a++;
    15             }
    16         }
    17         Child.prototype = new Parent(); 
    18         var parent = new Parent();
    19         var child1 = new Child();
    20         var child2 = new Child();
    21         child1.a = 11;
    22         child2.a = 12;
    23         parent.show();
    24         child1.show();
    25         child2.show();
    26         child1.change();
    27         child2.change();
    28         parent.show();
    29         child1.show();
    30         child2.show();

    这是一道非常好的面试题, 考察以下知识点:

    1,this的指向

    2,原型(prototype)以及原型链

    3,继承

    4,引用

    要解出这道题,要理解以下几句话就可以了:

    1,每一个构造函数,都有一个原型[[prototype]]属性 指向构造函数的原型对象

    2,每一个实例生成的时候,都会在内存中产生一块新的堆内存

    3,每一实例都有一个隐式原型__proto__ 指向构造函数的原型对象

    4,this的指向 取决于this调用时的位置, 在这道题中, 也可以简单理解为, 谁调用方法, this就指向哪个对象

    5,数组和字面量对象 都是 引用

    6,原型链的查找规则:  就近原则

    • 当实例上存在属性时, 用实例上的
    • 如果实例不存在,顺在原型链,往上查找,如果存在,就使用原型链的
    • 如果原型链都不存在,就用Object原型对象上的
    • 如果Object原型对象都不存在, 就是undefined

    为了帮助大家, 我贴出示意图, 如果有不理解的,欢迎互动,交流

  • 相关阅读:
    Linux-线程同步(day14续)
    Linux之线程(day14)
    Linux-网络编程-UDP网络编程(day13续2)
    ES6 模块加载
    let与var声明区别
    vue 常用指令v-if v-else v-show v-for
    动态路由的意义,以及路由重定向
    前端路由的理解
    socpe 与 包的引入
    VUE 组件注册(全局、局部)
  • 原文地址:https://www.cnblogs.com/ghostwu/p/7272132.html
Copyright © 2011-2022 走看看