Code Monkey home page Code Monkey logo

Comments (2)

lamelamb avatar lamelamb commented on June 22, 2024

new 可以视为语言上的语法糖,
1。不用手动新建一个obj ,new会帮你创建

2。不用把新建的obj的__proto__指向构造函数Common的prototype,new会帮你做。

3。构造函数this的作用域会指向实例本身。

4。不用手动return新建的obj,new会帮你return。

5。new出来的实例的__proto__会指向构造函数的prototype。构造函数的方法,实例可以直接调用

from daily.

MMmaXingXing avatar MMmaXingXing commented on June 22, 2024

介绍

new操作符可以快速创建构造函数的实例,以下

    function Person(name, age, job) {
        this.name = name;
        this.age = age;
        this.job = job;
    }

    Person.prototype.sayHello = () {
        alert("hello");
    }

    let man = new Person('zucker', 18, 'job')
    console.log(man);
    man.sayHello();

以上 经历了四个步骤,

1、内部创建一个新对象
2、将构造函数的作用域赋值给新对象,(设置原型链,因此this就指向了这个新对象)
3、执行构造函数中的代码
4、返回新对象

实现一个new对象

function New(obj, ...arr) {
    len ans = {};
    ans.__proto__ = obj.prototype; // 连接原型对象
    // Object.setPrototypeOf(ans, obj.prototype)

    // let ans = Object.create(obj.prototype);

    let result = obj.apply(ans, arr); //获得构造函数的返回值
    return ans === Object ? ans : result;
    // 判断构造函数的返回值是否与创造的实例不同 
}

from daily.

Related Issues (20)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.