zoukankan      html  css  js  c++  java
  • js中new 到底做了什么?

    1. 执行 new 一个对象需要经过的过程
      1. 创建一个新的对象
      2. 将构造函数的作用域付给新对象
      3. 为该对象添加属性
      4. return 该对象
    2. 举例
    // 构造函数写法
    function Parent(name, age) {
        this.name = name
        this.age = age
    }
    Parent.prototype.say = function() {
        console.log(this.name)
    }
    let child = new Parent('tutao', 25)
    
    child.say() //  tutao
    
    // class写法
    
    class Parent1 {
        constructor(name, age) {
            this.name = name
            this.age = age
        }
        say() {
            console.log(this.name)
        }
    }
    let child1 = new Parent1('tutao', 25)
    child1.say() // tutao
    
    1. 《javascript 模式》解释:当我们 new 一个构造器,主要有三步:
      1. 创建一个空对象, 将他的引用赋给 this,继承函数的原型
      2. 通过 this 将将属性和方法添加至这个对象
      3. 最后返回 this 指向的新对象,也就是实例
    2. 手动按照原理实现一个 new 方法
        const myNew = function (Parent, ...prop) {
    		let child = {}  // 创建一个空对象
    		child.__proto__ = Parent.prototype  // 空对象的引用赋给this
    		Parent.apply(child, prop)  // 属性和方法添加至新对象
    		return child   // return 新对象
    	}
        let child = myNew(Parent, 'tutao', 25)
        child.say() // tutao
    
  • 相关阅读:
    从开发者角色到产品角色转换
    前端开发做什么?
    最近的前端开发认知总结
    最近的Vue知识总结
    计算机网络
    javascript 字符串加密的几种方法
    JSON数据解析
    JAVA 自定义状态码
    JAVA jdbc获取数据库连接
    JAVA通过md5方法进行加密
  • 原文地址:https://www.cnblogs.com/tutao1995/p/14266076.html
Copyright © 2011-2022 走看看