zoukankan      html  css  js  c++  java
  • new关键字对构造函数做了什么

    在javascript中,new关键字能让一个函数变得与众不同,把new搞清楚了,就明白构造函数中的this指向谁了。

    举个例子

    funtion Demo(){
         console.log(this);
    }
    Demo();//window
    new Demo();//demo
    

    很显然使用new关键字之后,函数内部this的指向发生了变化,那么具体发生了什么变化呢,就得搞清楚new关键字究竟做了什么。

    function New(func){
         //声明一个中间对象,该对象为最终返回的实例
        var res = {};
        if(func.prototype != null){
        //将实例的原型指向构造函数的原型
       res.prototype = func.prototype;
       }
       //ret为构造函数执行的结果,这里通过```apply```,将构造函数内部的```this```指向修改为指向```res```,即实例对象
       var ret = func.apply(res,Array.prototype.slice.call(arguments,1));
       //当我们在构造函数上明确指定了返回对象时,那么```new```的执行结果就是该返回对象
       if((typeof ret === 'object' || typeof ret === 'function')&&ret != null){
              return ret;
       }
    return res;
    }
    

    所以在new一个实例的过程中,其实是执行了如下的步骤

    • 1、声明一个中间对象
    • 2、将该中间对象的原型指向构造函数的原型
    • 3、将构造函数中的this指向该中间对象
    • 4、返回该中间对象,即返回实例对象
  • 相关阅读:
    (六)Value Function Approximation-LSPI code (5)
    (六)Value Function Approximation-LSPI code (4)
    (六)Value Function Approximation-LSPI code (3)
    (六)Value Function Approximation-LSPI code (2)
    RSA1 密码学writeup
    攻防世界RE 2.666
    攻防世界RE 1.IgniteMe
    {DARK CTF }Misc/QuickFix
    {DARK CTF }forensics/AW
    攻防世界新手RE 12.maze
  • 原文地址:https://www.cnblogs.com/mcray/p/6640113.html
Copyright © 2011-2022 走看看