javascript - 在 Javascript 的构造函数中访问不是使用 'this' 关键字创建的变量

标签 javascript

<分区>

我正在寻找如何在不使用“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

关于javascript - 在 Javascript 的构造函数中访问不是使用 'this' 关键字创建的变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52431893/

相关文章:

javascript - jQuery 在文本有限时隐藏“显示更多”按钮

javascript - 在 div 和 textfield 之间切换时触发事件

java - 如何在rteplugins下为richtext组件添加图像插件

javascript - 使用 AngularJS 进行子域路由

javascript - 如何在globe d3.js上显示国家名称

javascript - 提交时从表单中删除未更改的输入字段

javascript - jQuery window.matchMedia 冲突函数

javascript - 向下遍历到下一个非直接且不同类型的元素

javascript - 我怎么知道最后一次异步何时完成?

javascript - typescript 错误 "Property ' 值'在类型 'HTMLElement' 上不存在”, "Property ' onclick'在类型 'Element' 上不存在”