如何在javascript对象中访问内部对象的属性

Nay*_*yan 1 javascript

这是我的代码:

function TaskRepository () {

    var self = this;

    var entity = {
        'startTime': 900,
        'endTime': 1830
    };

    this.setStartTime = function(sTime){
        self.entity.startTime = sTime;
    };

    this.getStartTime = function(){
        return self.entity.startTime;
    };
}
Run Code Online (Sandbox Code Playgroud)

但是以下代码不起作用

var x= new TaskRepository();
x.setStartTime(6);
Run Code Online (Sandbox Code Playgroud)

这有什么不对?我错过了什么?我也尝试过访问属性,self.entity['startTime']但这也无效.

Shi*_*lly 5

由于您将该函数用作构造函数,因此必须将实体设置为属性,而不是伪私有变量.如果您计划进行大量的这些taskRepos,您可以将这两种方法移动到原型.

function TaskRepository () {
    this.entity = {
        'startTime': 900,
        'endTime': 1830
    };
    this.setStartTime = function(sTime){
        this.entity.startTime = sTime;
    };
    this.getStartTime = function(){
        return this.entity.startTime;
    };
}
Run Code Online (Sandbox Code Playgroud)

要么

function TaskRepository () {
    this.entity = {
        'startTime': 900,
        'endTime': 1830
    };
}
TaskRepository.prototype = {
    'setStartTime' : function(sTime) {
        this.entity.startTime = sTime;
    },
    'getStartTime' : function(){
        return this.entity.startTime;
    }
};
Run Code Online (Sandbox Code Playgroud)