美文网首页
Javascript new 对象的过程

Javascript new 对象的过程

作者: LenHong | 来源:发表于2020-04-10 11:06 被阅读0次

    首先看一下下面的代码

    function User(name , age, career) {
        this.name = name
        this.age = age
        this.career = career 
    }
    const user = new User('ryan', 19, 'fe')
    console.log(user)  // {name: "ryan", age: 19, career: "fe"}
    
    function newUser(name , age, career) {
      return {
        name,
        age,
        career ,
      }
    }
    const newuser = newUser('ryan', 19, 'fe')
    console.log(newuser)  // {name: "ryan", age: 19, career: "fe"}
    

    想想这两种获取对象的方式有什么不同?

    再看看下面的代码

    function User(name , age, career) {
        this.name = name
        this.age = age
        this.career = career 
    }
    User.prototype.sayName = function () {
        console.log("Hello")
    }
    const user = new User('ryan', 19, 'fe')
    console.log(user)  // {name: "ryan", age: 19, career: "fe"}
    user.sayName() // Hello
    
    function newUser(name , age, career) {
      return {
        name,
        age,
        career ,
      }
    }
    newUser.prototype.sayName = function () {
        console.log("Hello")
    }
    const newuser = newUser('ryan', 19, 'fe')
    console.log(newuser)  // {name: "ryan", age: 19, career: "fe"}
    newuser.sayName() // Uncaught TypeError: newuser.sayName is not a function
    

    看到这里是不是感觉好像明白了什么

    new 的过程和普通的函数返回不同,new 其实是一种继承的方式, 通过new,实例与构造函数通过原型链连接了起来出来,所以实例能访问到构造函数的属性,具体过程如下

    1. 开辟一个块内存,创建一个空对象
    2. 执行构造函数,对这个空对象进行构造
    3. 给这个空对象添加proto属性
      __proto__ = User.prototype  
    

    相关文章

      网友评论

          本文标题:Javascript new 对象的过程

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