引用对象的变量 id 和使用 'this' 有什么区别吗?
Is there any difference between referencing a object's variable id and using 'this'?
具有以下代码,其中 fc
1 和 fc2
方法都应该 return 他们构建的对象中 x
属性 的值和 return (而不是来自 Foo 实例):
function Foo() {
this.x = 5;
}
Foo.prototype.fc1 = function() {
return {
x: 6,
getx() {
return this.x;
}
}
}
Foo.prototype.fc2 = function() {
const o = {
x: 6,
getx() {
return o.x;
}
}
return o;
}
在使用或引用对象内部的常量标识符方面,方法 fc1 和 fc2 之间是否有任何内部或相关差异,就像在 fc2 中所做的那样?
我倾向于 fc2 模式,因为对我来说似乎更干净(仅使用 this
对我来说听起来不错!)。性能不是问题,但无论如何,我很高兴知道是否必须考虑一些相关的因素。
母语不是英语,如果我不清楚请告诉我。此外,无法在 google 中进行正确的搜索。我没有登陆任何有用的文章。文章或文档的帮助将不胜感激。
谢谢。
在你的第二个例子中你使用了闭包。
关闭结束o
..这意味着this
甚至没有被使用。虽然它确实有优点,但它是您可以用来创建受保护对象/封装等的技巧。
举个例子,下面我把你的例子变成了一个工作片段。然后我在这两种情况下都引用了 getX
函数,然后调用它。您会注意到第一个 returns 未定义,但第二个因为您仍在使用闭包 returns 6
.
当然缺点是call
apply
& bind
对功能也没有影响。你选择哪一个当然取决于你想如何使用这个函数,在你的例子中使用 closure
似乎是一个更可靠的选择。理论上 closure
也可能有轻微的性能优势,这是因为 this
有一种叫做原型链的东西,这可以减慢速度..
function Foo() {
this.x = 5;
}
Foo.prototype.fc1 = function() {
return {
x: 6,
getx() {
return this.x;
}
}
}
Foo.prototype.fc2 = function() {
const o = {
x: 6,
getx() {
return o.x;
}
}
return o;
}
const f = new Foo();
console.log('calling foo.fc1.getx');
const fc1 = f.fc1().getx;
console.log(fc1());
console.log('calling foo.fc2.getx');
const fc2 = f.fc2().getx;
console.log(fc2());
具有以下代码,其中 fc
1 和 fc2
方法都应该 return 他们构建的对象中 x
属性 的值和 return (而不是来自 Foo 实例):
function Foo() {
this.x = 5;
}
Foo.prototype.fc1 = function() {
return {
x: 6,
getx() {
return this.x;
}
}
}
Foo.prototype.fc2 = function() {
const o = {
x: 6,
getx() {
return o.x;
}
}
return o;
}
在使用或引用对象内部的常量标识符方面,方法 fc1 和 fc2 之间是否有任何内部或相关差异,就像在 fc2 中所做的那样?
我倾向于 fc2 模式,因为对我来说似乎更干净(仅使用 this
对我来说听起来不错!)。性能不是问题,但无论如何,我很高兴知道是否必须考虑一些相关的因素。
母语不是英语,如果我不清楚请告诉我。此外,无法在 google 中进行正确的搜索。我没有登陆任何有用的文章。文章或文档的帮助将不胜感激。
谢谢。
在你的第二个例子中你使用了闭包。
关闭结束o
..这意味着this
甚至没有被使用。虽然它确实有优点,但它是您可以用来创建受保护对象/封装等的技巧。
举个例子,下面我把你的例子变成了一个工作片段。然后我在这两种情况下都引用了 getX
函数,然后调用它。您会注意到第一个 returns 未定义,但第二个因为您仍在使用闭包 returns 6
.
当然缺点是call
apply
& bind
对功能也没有影响。你选择哪一个当然取决于你想如何使用这个函数,在你的例子中使用 closure
似乎是一个更可靠的选择。理论上 closure
也可能有轻微的性能优势,这是因为 this
有一种叫做原型链的东西,这可以减慢速度..
function Foo() {
this.x = 5;
}
Foo.prototype.fc1 = function() {
return {
x: 6,
getx() {
return this.x;
}
}
}
Foo.prototype.fc2 = function() {
const o = {
x: 6,
getx() {
return o.x;
}
}
return o;
}
const f = new Foo();
console.log('calling foo.fc1.getx');
const fc1 = f.fc1().getx;
console.log(fc1());
console.log('calling foo.fc2.getx');
const fc2 = f.fc2().getx;
console.log(fc2());