2016-05-12 86 views
1

對不起,如果是重複的,但我沒有找到解釋。 如何在js類中創建字段?以定義未來...如何在javascript類中訪問字段

class Polygon { 
    //var whyNot; This makes false 
    constructor(height, width) { 
     this.height = height; 
     this.width = width; 
    } 

    calcArea() { 
    return this.height * this.width; 
    } 
} 
+0

? – War10ck

+0

我不這麼認爲 - 我在這裏找到了這個例子https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes,我試圖學習清晰的文檔。 – nolbadi111

+0

這個例子是ES6。我已將標籤添加到您的問題中,以提高其可見度。 – War10ck

回答

-2

檢查此答案。 Constructors in JavaScript objects

您在javascript中沒有'class',您將該對象定義爲函數。你將可繼承的函數定義爲原型。幾乎你會使用'原型'關鍵字來控制oop行爲。

+2

從ES6開始,JavaScript確實有類:http://stackoverflow.com/questions/28308578/member-variables-in-es6-classes – War10ck

0

您對JS對象的理解有點偏離......您創建了一個調用它自己的構造函數的函數的變量。然後修改對象以包含稍後希望調用的函數。像這樣https://jsfiddle.net/programndial/vonc5af5/

<input type="button" id="testButton" value="Test" /> 

function Polygon(height, width) { 
    this.height = height; 
    this.width = width; 

    Polygon.prototype.calcArea = function(string) { 
     return this.height * this.width; 
    } 
} 

testButton.onclick = function() { 
    var newPoly = new Polygon(10, 25); 
    alert(newPoly.calcArea()); 
} 
+0

我沒有創建一個調用它自己的構造函數的函數的變量。之後「爲什麼不可變varaiable是否=構造函數等。我試圖做一些像」whyNot = 3;「的字段但我不能。 – nolbadi111

+0

@ nolbadi111即時通訊只是說你的js類構造關閉..看看[這個小提琴](https://jsfiddle.net/programndial/82zhgf8h/)你可以做到你想要的。 – programndial

+0

@ nolbadi111只記得用var聲明的成員是私有的,只能通過'class'方法修改..如果你想要一個公共屬性,你必須使用this.whyNot – programndial

0

答案是(部分)在你的問題中。

我們將從您的評論中的代碼和鏈接中假設您使用最新版本的Javascript:ES6或ES2015。

您可以按照您提供的代碼在constructor方法中創建它們。

class Polygon { 

    constructor(height, width) { 
     //height and width will be fields of Polygon 
     this.height = height; 
     this.width = width; 
     //...and whyNot too! 
     this.whyNot = 42; 
    } 

    ... 

當然,既然是ES6兼容的JavaScript以前的版本仍然可以您是否使用ES6,打字稿等使用constructor methods, object literals...