Javascript - 在对象中调用对象的方法给出错误:'对象没有方法getStartPoint'

时间:2013-10-27 05:31:04

标签: javascript javascript-objects

如何在startPoint中调用 getStartPoint(),在下面的代码中?

var obj = (function () {
    return {
        defaults: {
            prop: {
                getStartPoint: function () {
                    // more login ...
                },
                getEndPoint:   function () {
                    // more login ...
                },
                startPoint: this.getStartPoint(),
                endPoint:   this.getEndPoint(),
            }
        }
    };
})();

我收到错误

  

Uncaught TypeError:Object ...没有方法'getStartPoint'

所有这些:getStartPoint(),this.getStartPoint(),obj.defaults.prop.getStartPoint()

1 个答案:

答案 0 :(得分:0)

一种可能的解决方案:

var obj = (function () {
    function getStartPoint() {
        console.log("getStartPoint");
    }
    function getEndPoint() {
        console.log("getEndPoint");
    }
    return {
        defaults: {
            prop: {
                getStartPoint: getStartPoint,
                getEndPoint: getEndPoint,
                startPoint: getStartPoint(),
                endPoint: getEndPoint()
            }
        }
    };
})();

另:

function Obj() {
    if (!(this instanceof Obj)) return new Obj();
    this.defaults = {
        prop: {
            startPoint: this.defaults.prop.getStartPoint(),
            endPoint: this.defaults.prop.getEndPoint()
        }
    };
}

Obj.prototype = {
    defaults: {
        prop: {
            getStartPoint: function () {
                console.log("getStartPoint");
            },
            getEndPoint: function () {
                console.log("getEndPoint");
            }
        }
    }
};

var obj = new Obj();