<!DOCTYPE html>
<html lang="en">
<head>
<title>latihan 2 Objek</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
<script type="text/javascript">
function timeObjc(hour,minute,second){
this.hour= hour;
this.minute = minute;
this.second= second;
this.setTime= function(whathour,whatminute,whatscnd){
this.hour=whathour;
this.minute =whatminute;
this.second =whatscnd;
};
this.runTime = function(){return this.hour+":"+this.minute+":"+this.second};
}
timeObjc.setTime(10,22,36);
timeObjc.runTime();
</script>
</body>
</html>
我想在函数外手动设置时间并使用 runTime 函数打印它,但它保留错误,指出“setTime 不是函数”..我很高兴知道我错过了什么以及为什么会发生这种情况。提前致谢
你还没有初始化你的timeObjc
。而您正试图setTime
作为静态方法运行,但事实并非如此。
您必须首先初始化对象,然后运行其setTime
函数。
function timeObjc(hour,minute,second){
this.hour= hour;
this.minute = minute;
this.second= second;
this.setTime= function(whathour,whatminute,whatscnd){
this.hour=whathour;
this.minute =whatminute;
this.second =whatscnd;
};
this.runTime = function(){return this.hour+":"+this.minute+":"+this.second};
}
var obj = timeObj(1,1,1)
obj.setTime(10,22,36);
obj.runTime();
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句