簡體   English   中英

我們如何訪問 ES6 class 中的私有變量?

[英]How do we get access to a private variable in ES6 class?

下面我們為 class 'Forrest' 的可能實例定義一個私有變量boy 通過這樣做 JavaScript 信號沒有錯誤。 但是實例、 Forrest.prototypeForrest function object 本身都沒有顯示托管此變量的跡象。

class Forrest {
  constructor() {
    let boy = "Bobby";
    girl: "Marry";
  }
}

const f = new Forrest();

但是,我們可以通過 vanilla JS 構造函數 function 輕松訪問這個私有boy變量。

function Forrest() { 
  let boy = "Bobby"; 
  this.getBoy = function() { 
    console.log(boy);
  } 
} 

const f = new Forrest();
f.getBoy(); // Bobby 

我們如何在 ES6 class 中訪問這個私有(本地)變量?

let boy是一個僅在構造函數的 scope 中有效的變量

girl: "Marry"根本不是財產

這是您初始化和訪問屬性的方式

 class Forrest { constructor() { this.boy = "Bobby" this.girl = "Marry" } } const f = new Forrest(); console.log(f.boy) console.log(f.girl)

// 答案是:

class Forrest {
  constructor() {
    let boy = "Bobby"
    this.getBoy = function() { // This is it!
      console.log(boy)
    }
  }

}

const f = new Forrest()
f.getBoy() // Bobby

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM