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
    
  • 相关阅读:
    Code Forces Gym 100886J Sockets(二分)
    CSU 1092 Barricade
    CodeChef Mahesh and his lost array
    CodeChef Gcd Queries
    CodeChef GCD2
    CodeChef Sereja and LCM(矩阵快速幂)
    CodeChef Sereja and GCD
    CodeChef Little Elephant and Balance
    CodeChef Count Substrings
    hdu 4001 To Miss Our Children Time( sort + DP )
  • 原文地址:https://www.cnblogs.com/tutao1995/p/14266076.html
Copyright © 2011-2022 走看看