[英]Should you use this. in reference to a property in factory functions?
大家,我正试图围绕工厂功能。 我想知道制作一个接受参数的工厂 function 的正确方法是什么。
我们给它创建的对象的方法是否应该通过使用 this 来引用它的属性。 在他们面前?
例如:
//using this.
function createPerson(name) {
return {
name,
talk() {
console.log(this.name);
}
}
}
或者这样:
//not using this.
function createPerson(name) {
return {
name,
talk() {
console.log(name);
}
}
}
我都尝试过,它们似乎都以相同的方式执行,我认为我可能错了。 意思是如果我运行以下命令:
const marc = createPerson('marc');
const joe = createPerson('joe');
marc.talk();
joe.talk();
在这两种情况下,我得到相同的 output,所以有必要使用它。 在工厂 function? 常见的做法是什么? 感谢你们对我的帮助
您的用例正在使用this
只是因为返回的 object 具有该name
属性。
上下文是返回this
object 而不是 createPerson function object
如果您要在 object 之外有一个变量并尝试使用this
访问它,它将无法正常工作。
上下文this
很复杂,我认为您很容易混淆知道this
是什么在您的用例中
//not using this. function createPerson(name) { // without using new createPerson() "this" is not the function object const upper = this.upper = name.toUpperCase(); return { name, talk() { console.log('this.upper', this.upper) console.log('upper', upper); } } } const foo= createPerson('foo') foo.talk()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.