• 学生问的一道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

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

  • 相关阅读:
    memcache 基本操作
    PHP 实现定时任务的几种方法
    PDO 事务处理
    mysql命令gruop by报错this is incompatible with sql_mode=only_full_group_by
    ASP.NET Web API 跨域访问(CORS)
    nmap使用
    买定离手,落子无悔
    html5plus处理返回键
    PAT 1008 数组元素循环右移问题
    PAT 1007 素数对猜想
  • 原文地址:https://www.cnblogs.com/ghostwu/p/7272132.html
Copyright © 2020-2023  润新知