[英]Is it possible to create a property from another property within the same prototype object?
New to coding: I'm trying to do something like this in Javascript: 编码新手:我正在尝试使用Javascript做类似的事情:
function Calculator(a,b){
this.a=a;
this.b=b;
this.c=a*b;
this.d=c;
}
var myTiCalc = new Calculator(1,2);
alert(myTiCalc.d);
So that it prints "d" in an alert box. 这样它将在警报框中显示“ d”。 However I keep getting a "Nan" in the alert. 但是,我在警报中不断收到“ Nan”。
Appreciate your expertise! 感谢您的专业知识!
You will need to assign the var c
. 您将需要分配var c
。
Or you can do this.d = this.c;
或者您可以执行此操作this.d = this.c;
function Calculator(a,b){ this.a=a; this.b=b; this.eg = a*b; var c = a*b; this.d=c; this.d2 = this.eg; } var myTiCalc = new Calculator(1,2); console.log(myTiCalc.d); console.log(myTiCalc.d2);
function Calculator(a,b){ this.a=a; this.b=b; this.c=a*b; this.d=this.c; } var myTiCalc = new Calculator(1,2); alert(myTiCalc.d);
In the line #5 you put this.d=c;
在第5行中,您将this.d=c;
instead of this.d=this.c
. 代替this.d=this.c
Variable c
was not defined anywhere. 变量c
在任何地方都没有定义。 What I think you need is to assign property c
to d
of the Calculator object, so you need to call it with the this
keyword. 我认为您需要将属性c
分配给Calculator对象的d
,因此您需要使用this
关键字进行调用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.