如何使用构造函数's的输出,以便将值插入到对象中
how to use a constructor function's output to insert values to an object?
我为一个圆创建了一个构造函数,其中有一个半径值,还有两个函数来计算面积和周长,我试图将面积和周长的计算值作为要构建的对象的元素传递,但它不起作用。
function Circle (r) {
this.radius = r;
this.area = function () {
var a = Math.PI * this.radius * this.radius;
// tried this
this.areaaaa = a;
};
this.perimeter = function(){
var p = Math.PI * this.radius * 2;
// tried this too
this.perimeterrrr = p;
};
};
var x = new Circle(5);
console.log(x);
// output is {radius:5, area: [function], perimeter: [function]}
// desired output is {radius:5, area: [function],areaaa:78.54, perimeter: [function], perimeterrrr:31.42}
您可以使用ECMA 6 getter和setter
function Circle (r) {
this.radius = r;
Object.defineProperty(this, "area", { get: function () { return Math.PI * this.radius * this.radius; } })
};
var circle = new Circle(5)
circle.radius //5
circle.area //78.53981633974483
问题是这些函数定义中的代码永远不会运行。试试这个。
function Circle (r) {
this.radius = r;
this.a = Math.PI * this.radius * this.radius;
this.p = Math.PI * this.radius * 2;
};
var x = new Circle(5);
console.log(x);
相关文章:
- 在数组中插入对象失败
- 如何将对象插入对象列表的开头,当它有 unshift 不是函数错误
- 将新数据项插入对象
- 如果我可以随时将任何属性插入对象,那么在javascript中创建类有什么用
- 在 javascript 的数组中插入对象
- MongoDB Node - 获取插入对象的_id
- 在 Meteor 中,如何使表单加载从先前从 MongoDB 集合中提取的插入对象预填充
- 如何在 JavaScript/JSON 中插入对象的键名
- 在HTML中插入对象数据
- 使用Node.js在现有Mongoose模式中插入对象ID's到数组中
- 如何插入对象到Firebase锻造?- AngularFire 0.8.0 - Thinkster -第7章
- 在指定位置的对象数组中插入对象数组
- 无法在javascript中插入对象到JSON对象
- javascript:如何插入对象到innerHtml
- 如何在elasticsearch中插入对象数组
- JavaScript警告在插入对象到数组后不工作
- 插入对象(jquery)延迟
- 在数组元素之间插入对象的最优雅的方式是什么?
- 在数组中插入对象
- 插入对象时myStorage是undefined错误