我怎么能访问javascript对象上的setter和getter?

时间:2017-06-30 08:24:34

标签: javascript oop

<!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函数打印它,但它会保留错误,表示&#34; setTime不是函数&#34; .. 我很高兴知道我失踪了,为什么会这样。 提前谢谢

2 个答案:

答案 0 :(得分:0)

您尚未初始化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();

答案 1 :(得分:0)

使用new关键字创建新对象。

var timeObject = new timeObjc(11, 22, 33) 然后timeObjc.setTime(2,3,4)