new的原理是什么?通过new方式创建对象和通过字面量创建有什么区别?

1.new的原理是什么?
看这里

2.new创建对象和字面量创建本质上是一样的,字面量的方式比较简单,也不用调用构造函数,性能较好

3.自己模拟new的操作

function Person(type) {
     
        this.type = type;
        // return 10;//Primitive value returned from constructor will be lost when called with 'new'
        // return {age:20};
    }
/**
 * mockNew(构造器,构造器参数)
 */
function mockNew() {
     
        let Constructor = [].shift.call(arguments);//拿到第一个参数(构造器)
        let obj = {
     };//创建一个对象
        obj.__proto__ = Constructor.prototype;//将新创建的对象的原型指向Constructor的prototype
        let res = Constructor.apply(obj,arguments);//调用Constructor并将其他参数传入
        //判断构造函数返回值的类型,若为object类型则返回res,若res为基本数据类型,则返回obj
        return res instanceof Object ? res : obj;
    }

以下两种方式创建对象都是阔以的

let p = new Person('哺乳类');
    console.log(p);
let p = mockNew(Person,'哺乳类');
    console.log(p);

你可能感兴趣的:(js基础,new,字面量)