我正在寻找如何在不使用“this”关键字的情况下访问构造函数内的变量。如果我把它放在变量前面,一切正常。
function MyQueue() {
this.collection = [];
this.index = 0;
}
MyQueue.prototype.isEmpty = function () {
return this.collection.length === 0;
}
但是,如果我去掉这个关键字,我在创建对象时就无法到达collection和index。有什么方法可以达到这些变量吗?
function MyQueue ()
{
let collection = [];
let index = 0;
}
MyQueue.prototype.isEmpty = function()
{
return this.collection.length === 0;
}
这个不行。如何在构造函数中访问集合和索引?提前致谢。
If I put this in front of the variables, everything works fine.
在这种情况下,您要向队列对象添加属性。任何引用该对象的东西也将能够获得它的属性
However, if I remove the this keyword, I can't reach collection and index when I create a object.
在这种情况下,您正在创建局部变量。它们将仅在当前函数以及任何嵌套函数中的代码范围内。
Is there any way to reach these variables?
仅在构造函数和任何嵌套函数中。通过嵌套函数,我的意思是如果你愿意,你可以这样做:
function MyQueue () {
let localVariable = 3;
this.logLocalVariable = function() {
console.log(localVariable);
}
}
const queue = new MyQueue();
queue.logLocalVariable(); // logs 3;
console.log(queue.localVariable) // logs undefined