2016-05-12 82 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...