• 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
    
  • 相关阅读:
    istio kiali 亲和性调度
    istio kiali 内部介绍
    istio kiali 可视化bookinfo
    Istio 部署Bookinfo 应用
    初探istio kiali
    安装Istio
    Istio 是什么?
    AQS源码浅析
    go 单元测试testify
    go unknown revision报错
  • 原文地址:https://www.cnblogs.com/tutao1995/p/14266076.html
Copyright © 2020-2023  润新知