zoukankan      html  css  js  c++  java
  • new和this

    new和this

      当new一个新的数据的时候,new操作符的流程

        1、首先创建实例对象{}

        2、this变量引入该对象,同时还继承了构造函数的原型

        3、其次属性和方法被加入到this引用的对象中

        4、并且新创建的对象由this所引用,最后隐式的返回this

    function objectFactory() {
    
        var obj = new Object(),//从Object.prototype上克隆一个对象
    
        Constructor = [].shift.call(arguments);//取得外部传入的构造器
    
        var F=function(){};
        F.prototype= Constructor.prototype;
        obj=new F();//指向正确的原型
    
        var ret = Constructor.apply(obj, arguments);//借用外部传入的构造器给obj设置属性
    
        return typeof ret === 'object' ? ret : obj;//确保构造器总是返回一个对象
    
    };

      

     

      this对象的理解

        普通函数

          this总是指向函数的直接调用者

          如果有new关键字,this指向new出来的实例对象

          在事件中,this指向触发这个事件的对象

          IE下attachEvent中的this总是指向全局对象Window

          箭头函数中,函数体内的this对象,就是定义的时候所在作用域的对象,而不是使用的时候所在的作用域对象

    function foo() {
      console.log(this.a)
    }
    var a = 1
    foo()           //1       
    ​
    const obj = {
      a: 2,
      foo: foo
    }
    obj.foo()      //2
    ​
    const c = new foo()   //undefined

        对于直接调用foo来说,不管foo函数被放在了什么地方,this一定是window

        对于obj.foo()来说,我们只需要记住,谁调用了函数,谁就是this,所以在这个场景下foo函数中的this就是obj对象

        对于new的方式来说,this被永远绑定在了new出来的对象上,不会被任何方式改变this

      箭头函数中的this

    function a() {
      return () => {
        return () => {
          console.log(this)
        }
      }
    }
    a()()()        //Window

        首先箭头函数其实是没有this的,箭头函数中的this只取决包裹箭头函数的第一个普通函数this。在这个例子中,因为包裹箭头函数的第一个普通函数是a,所以这个时候this指向的就是window。另外对箭头函数使用bind这类函数是无效的。

      

  • 相关阅读:
    WPF之感触
    C# WinForm 给DataTable中指定位置添加列
    MyEclipse 8.6 download 官方下载地址
    将博客搬至CSDN
    Building Microservices with Spring Cloud
    Building Microservices with Spring Cloud
    Building Microservices with Spring Cloud
    Building Microservices with Spring Cloud
    Building Microservices with Spring Cloud
    Building Microservices with Spring Cloud
  • 原文地址:https://www.cnblogs.com/tulintao/p/13584461.html
Copyright © 2011-2022 走看看