【发布时间】:2018-08-21 16:00:02
【问题描述】:
我正在学习如何使用 JavaScript 创建对象和类,对于在代码中创建过多注释,我深表歉意。这是为了帮助我记住重要的概念。我对 JavaScript 很陌生!我的问题是,我试图从类或对象外部访问函数,但如果没有语法错误,我似乎无法做到这一点。我假设是因为变量或方法超出了范围。那么我该如何调用类中存在的方法呢?我希望对象显示我创建的任何对象的周长。请帮忙!
class ball {
// get method used to access properties about the class/object
get ballInfo() { // constructor name should be about the objects behavor or algorithem.
this.radius = undefined;
this.diameter = undefined; // default values for undeclared values or strings should be kept as 'undefined'. For objects use 'null' instead.
this.pie = 3.14;
// defining variables that can be used out of scope for the functions below:
let displayDiameter = theDiameter(diameter);
let displayRadius = theRadius(radius);
// function1of2:
function theDiameter(diameter) {
let circumferenceTwo = pie*diameter;
return circumferenceTwo;
// function2of2
function theRadius(radius) {
let circumferenceOne = 2*pie*radius;
return circumferenceOne;
if (this.radius = undefined) {
/* NOTE: calling this method outside of this class or object
will give you the 'unexpected identifer error' because it is out of scope!
*/
console.log("The circumference for the ball is (msg1)" + (displayDiameter(6)));
// The fact that it's not outputting the console.log statement implies that the argument is not true for the if statement
}
if (this.diameter = undefined) {
console.log("The circumference for the ball is (msg2)" + (displayRadius(4)));
}
// Unfornately I can't seem to find a way to display the diameter on the screen.
console.log("displaying the circumference using the diameter.... " + displayDiameter(6));
} // end of theRadius function
} // end of theDiameter function
} // end of ballInfo function
}; // end of class
【问题讨论】:
-
为什么
theRadius在theDiameter中声明?没有意义。 -
是的,当使用普通函数调用时,
this未定义。您需要将其作为方法调用,或使用箭头函数。 -
"我正在尝试从类或对象外部访问函数" - 请添加实例化
ball并尝试访问 (调用?)函数? -
我正在创建对象: let basketBall = new ball ();然后调用它: basketBall.ballInfo.displayDiameter(6);但我一直收到如下错误:Uncaught ReferenceError: diameter is not defined at ball.get ballInfo [as ballInfo] (index3.js:136) at index3.js:202
-
是的,在评估
basketBall.ballInfogetter 时,let displayDiameter = theDiameter(diameter)行确实会抛出该错误,因为参数diameter没有在任何地方声明
标签: javascript function object