[英]"This" in Factory Functions
如果这是一个非常愚蠢的问题,我很抱歉。 我已经搜索过它,但找不到明确的答案。 网络上的教程中有一个工厂函数,如下所示。 我已经大致了解“ This
”如何在其他地方工作,但我无法完全理解“ This
”如何帮助我们。 即使我删除了“ This
”,代码仍然有效。 我也不明白为什么删除“ return color;
”会破坏“ color.rgb()
”。
function makeColor(r, g, b) {
const color = {};
color.r = r;
color.g = g;
color.b = b;
color.rgb = function () {
//const { r, g, b } = this;
return `rgb(${r}, ${g}, ${b})`;
};
return color;
}
const newColor = makeColor(50, 100, 150);
newColor.rgb();
console.log(newColor); // {r: 50, g: 100, b: 150, rgb: ƒ}
console.log(newColor.rgb()); //rgb(50, 100, 150)
即使我删除了“这个”,代码仍然有效
我假设你的意思是它仍然适用于注释掉的这一行
//const { r, g, b } = this;
原因是您基本上对变量r
、 g
和b
有一个闭包,因此您仍然可以读取它们。
我也不明白为什么要删除“返回颜色”; 打破“color.rgb()”。
删除返回行会破坏一切,因为现在您的makeColor
函数返回未定义:
function makeColor(r, g, b) { const color = {}; color.r = r; color.g = g; color.b = b; color.rgb = function () { //const { r, g, b } = this; return `rgb(${r}, ${g}, ${b})`; }; //return color; } const newColor = makeColor(50, 100, 150); //newColor.rgb(); console.log(newColor); // undefined //console.log(newColor.rgb()); //rgb(50, 100, 150)
行return color
返回具有属性r
、 g
、 b
和函数rgb()
当你删除const { r, g, b } = this;
, rgb(${r}, ${g}, ${b})
引用了您分配给color
的makeColor
的参数。
当您调用makeColor
,它会执行函数中的任何操作,然后返回一个值。 在您的情况下,该值是在makeColor
定义的color
对象。 如果删除返回,它将返回undefined
const { r, g, b } = this;
在这一行中, this
指的是创建的对象实例,如果删除此行,它将起作用,因为函数方法中的参数名称与构造对象的属性名称匹配。 这就是代码“有效”的原因。
function makeColor(r, g, b) { const color = {}; color.r = r; color.g = g; color.b = b; color.rgb = function () { //const { r, g, b } = this; return `rgb(${r}, ${g}, ${b})`; }; return color; } const newColor = makeColor(50, 100, 150); newColor.rgb(); console.log(newColor); // {r: 50, g: 100, b: 150, rgb: ƒ} newColor.b = 0; console.log(newColor.rgb()); // this still prints 150 where it should print 0 // cause b refers to the argument passed into the makeColor function not instance member function makeColor2(r, g, b) { const color = {}; color.r = r; color.g = g; color.b = b; color.rgb = function () { const { r, g, b } = this; return `rgb(${r}, ${g}, ${b})`; }; return color; } const newColor2 = makeColor2(50, 100, 150); newColor2.b = 0; console.log(newColor2.rgb()); // b is 0 as expected
对于第二个问题,工厂方法是构建一些东西,然后通过从函数返回它来生产那个东西。 如果你不归还它,它就会留在本地,根本没有用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.