一道关于面向对象面试题所引发的血案(阿里)

<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="ie=edge" />
    <meta
      name="viewport"
      content="width=device-width, user-scalable=no, initial-scale=1.0"
    />
    <title></title>
    <!-- IMPORT CSS -->
  </head>

  <body>
    <!-- IMPORT JS -->
    <script>
      function Foo() {
        getName = function () {
          console.log(1);
        };
        return this;
      }
      Foo.getName = function () {
        console.log(2);
      };
      Foo.prototype.getName = function () {
        console.log(3);
      };
      var getName = function () {
        console.log(4);
      };

      function getName() {
        console.log(5);
      }
      Foo.getName(); //2
      getName(); //4
      Foo().getName(); //1
      getName(); //1
      new Foo.getName();
      2;
      new Foo().getName(); //3
      new new Foo().getName(); //3
    </script>
  </body>
</html>

 对象成员访问级别高,优先执行,new函数级别低,次之执行

2.

      function A() {
        alert(1);
      }
      function Func() {
        A = function () {
          alert(2);
        };
        return this;
      }
      Func.A = A;
      Func.prototype = {
        A: () => {
          alert(3);
        },
      };
      A();  //1
      Func.A(); //1
      Func().A();//2
      new Func.A();//1
      new Func().A(); //3
      new new Func().A();  //报错,箭头函数没有原型链,不能new

3.

// TO-STRING
        // 1.手动添加一个toString方法,每次判断==都会自动调用toString方法
         var a = {
            i: 0,
            toString() {
                return ++this.i;
            }
        };

        // a为什么,以下成立
        if (a == 1 && a == 2 && a == 3) {
            console.log('条件成立');
        } 

        /* var a = [1, 2, 3];
        a.toString = a.shift;
        if (a == 1 && a == 2 && a == 3) {
            console.log('条件成立');
        } */


        /* 2.数据劫持实现 */
        var i = 0;
        Object.defineProperty(window, 'a', {
            get() {
                return ++i;
            }
        });
        if (a == 1 && a == 2 && a == 3) {
            console.log('条件成立');
        } 

        /* var a = 0;
        Object.defineProperty(window, 'a', {
            get() {
                // Uncaught TypeError: Cannot redefine property: a
                // defineProperty GETER拦截器中不能再次获取当前属性,会死循环
                return ++a;
            }
        });
        console.log(a); */

总结

== ,数据类型不一样
1.对象==字符串, 对象自动调用toString变成字符窜 ['a']=='a'
2. null ==undefind相等,但是和其他值比较不在相等了
3,NaN ==NaN,不相等
4.剩下的都是转换成数字 '1'==true //true
[10]==10 ,底层转换
[10]自动调用toString为‘10’,然后自动调用number,为10
原文地址:https://www.cnblogs.com/fsg6/p/14531907.html