美文网首页
new 关键字 执行流程

new 关键字 执行流程

作者: 灯下草虫鸣314 | 来源:发表于2020-06-18 14:18 被阅读0次

    new 实例化过程到底执行了什么具体流程呢?

    在日常开发过程中我们常常会使用 new 关键字来实例化一个对象

    • 首先来一段代码
    function Person(name, age){
      this.name = name
      this.age = age
    }
    Person.prototype.sayName = function(){
      console.log('Hello, my name is ' + this.name);
    }
    const person = new Person('wu',26)
    person.sayName()
    
    • 在实例化一个 Person 过程中。javascript具体有以下4步操作:
    1. 创建一个空对象
     const person = {}
    
    1. 将对象obj的__proto__指向构造函数的prototype
     person.__proto__ = Person.prototype
    
    1. 将构造函数中的this指向这个obj并且执行构造函数代码,给对象obj添加属性、方法等
      Person.call(person, 'wu', 26)
    
    1. 返回这个对象
      return person
    

    使用new 关键字调用一个方法和直接调用一个方法有什么区别呢?

    • 首先看以下代码
    function NewObject(name){
      console.log('NewObject')
      this.name = name,
      this.sayName = ()=>{
        console.log('my name is '+ this.name)
      }
    }
    
    const nb = new NewObject('123')
    console.log(nb)   // Object
    nb.sayName()  // 123
    const nb2 = NewObject('456')
    console.log(nb2)   // undefined
    window.sayName()  // 456
    // nb2.sayName()    // 报错 
    

    我们通过两种方法调用了NewObject方法。
    使用new关键字调用时 我们可以找到 NewObject方法原型链上的sayName方法,而直接调用则会报错。但是,在window中调用反而成功了,这是为什么呢?

    这就是第一个问题讲到的,new关键字调用方法,会将方法调用时的this替换为实例化的对象。所以函数调用后会返回一个对象,这个对象会继承构造函数NewObject的原型链。
    而直接调用改函数执行NewObject函数后,没有任何返回值。则返回undefined, undefined是没有sayName()方法的,所以会报错。而且直接调用NewObject方法时this指向window所以用window.sayName()是可以正常执行的。

    使用 new 关键字调用函数是如何返回的呢?

    • 看以下代码
    function Animal(name){
      this.name = name
      return name
    }
    var animal1 = Animal('cat');
    
    var animal2 = new Animal('tiger');   
    var animal3 = new Animal(123) 
    var animal4 = new Animal(true)  
    var animal5 = new Animal({lastName:'mimi'})  
    var animal6 = new Animal([])
    var animal7 = new Animal(function(){})
    console.log(animal1)  // String cat 
    
    console.log(animal2)  // Object {name: 'tiger'}
    console.log(animal3)  // Object {name: 123}
    console.log(animal4)  // Object {name: true}
    
    console.log(animal5)  // Object  {lastName:'mimi'}
    console.log(animal6)  // Array  []
    console.log(animal7)  // Function  f(){}
    

    根据输入结果,我们可以知道。使用new关键字调用函数时,如果return的是NumberStringBoolean类型的字段则返回new关键字实例化的对象,而如果return的是ObjectArrayFunction、则直接返回这些字段本身。

    相关文章

      网友评论

          本文标题:new 关键字 执行流程

          本文链接:https://www.haomeiwen.com/subject/ttluxktx.html