JavaScript工厂模式出现undefined值问题排查及代码解析
工厂模式中出现undefined的原因及解决方法
先直接说你的代码里的核心问题:你在工厂函数里把属性赋值给了this,但最后返回的是独立的temp对象,而且printPerson方法里的this指向的是temp,不是你赋值属性的那个上下文,这就导致打印时找不到对应属性,输出undefined。
具体原因拆解:
- 当你直接调用
peopleFactory()(没有用new关键字)时,函数内部的this在浏览器环境中指向全局对象window,你写的this.name = name实际上是给window对象加了属性,和你最终要返回的temp对象完全没关系。 temp.printPerson方法里的this,在执行person1.printPerson()时会指向person1(也就是temp对象),但temp对象上并没有name、age、height这些属性,所以打印时自然就输出undefined了。
修正后的代码
把属性直接挂载到要返回的temp对象上,而不是this:
var peopleFactory = function(name, age, height) { var temp = {}; // 将属性直接绑定到temp对象上 temp.name = name; temp.age = age; temp.height = height; temp.printPerson = function() { console.log(`${this.name} ${this.age} ${this.height}`); document.write(`${this.name} ${this.age} ${this.height}<br>`); }; return temp; }; var person1 = peopleFactory('tanmay', 27, 5.11); var person2 = peopleFactory('chinmay', 37, 5.12); person1.printPerson(); person2.printPerson();
额外小优化说明
我把字符串拼接改成了ES6模板字符串,可读性更好;还给document.write加了<br>标签,避免两次输出的内容挤在一起。如果之后想改用构造函数模式(依赖new关键字),也可以调整,但你这里明确用工厂模式,核心就是要把属性绑定到最终返回的对象上。
内容的提问来源于stack exchange,提问作者S.T MOHANTY
相关产品推荐
相关产品推荐

