JavaScript 一篇文章搞清构造模式和工厂模式(new 做了什么操作)

工厂模式

        function createPerson(name, age, city) {
    
    
            let warp = new Object();
            warp.name = name;
            warp.age = age;
            warp.city = city;
            warp.showInfo = function () {
    
    
                return `${
      
      this.name}_${
      
      this.city}`;
            };
            return warp;
        };
        const cp1 = createPerson('tom', 18, '成都');
        const cp2 = createPerson('jerry', 24, '西安');
        console.log(cp1.showInfo()); // tom_成都
        console.log(cp2.showInfo()); // jerry_西安

构造模式

        function Person(name, age, city) {
    
    
            this.name = name;
            this.age = age;
            this.city = city;
            this.showInfo = function () {
    
    
                return `${
      
      this.name}_${
      
      this.city}`;
            };
        };
        const p1 = new Person('tom', 18, '成都');
        const p2 = new Person('jerry', 24, '西安');
        console.log(p1.showInfo()); // tom_成都
        console.log(p2.showInfo()); // jerry_西安
        console.log(p1.constructor === Person); // true
        console.log(p2.constructor === Person); // true

区别

  1. 没有return;
  2. 没有显示的创建对象;
  3. 属性和方法直接赋值给this;

注意点
1.构造函数名称首字母大写
2.工厂模式解决了创建多个类似对象的问题 但没有解决对象标识问题(即新创建的对象是什么类型 --> 创建来源)
3.相比工厂模式 自定义构造函数就可以确保被标识为特定类型(即constructor本来就是用于标识对象类型的)

new 操作符做了什么动作 (该内容在摘自《JavaScript高级程序设计》第八章)
1.在内存中创建一个新对象;
2.新对象内部的原型[[Prototype]]特性被赋值为构造函数的prototype属性;
3.构造函数内部的this 被赋值为这个新对象(即this指向新对象);
4.执行构造函数的内部代码(给新对象添加属性、方法);
5.如果构造函数返回非空对象,则返回该对象; 否则,返回刚创建的新对象。

过程模拟

   function create(fn, ...args) {
    
    
            // 创建一个空的对象
            let obj = Object.create(null);
            // 将空对象指向构造函数的原型链
            Object.setPrototypeOf(obj, fn.prototype);
            // obj绑定到构造函数上,便可以访问构造函数中的属性,即obj.fn(args)
            let result = fn.apply(obj, args);
            console.log(result, '返回结果'); 
            // 如果返回的result是一个对象则返回
            // new方法失效,否则返回obj
            return result instanceof Object ? result : obj;
        };
        // 验证
	 	const cache = create(Person, 'tom', 18, '成都');
        console.log(cache, '构造模式');

        console.log('---------------------')

        const cache1 = create(createPerson, 'tom', 18, '成都');
        console.log(cache1, '工厂模式');

返回结果
在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/qq_45284938/article/details/127387640
今日推荐