简体   繁体   English

无法访问对象方法

[英]Can't access object method

I've created a quasi namespace/class called NewsCalendar. 我创建了一个名为NewsCalendar的准命名空间/类。 My intent is to avoid polluting the global namespace as well as hide functions that should be private. 我的目的是避免污染全局命名空间以及隐藏应该是私有的函数。 But when I try to call what should be a public method I get "Object does not support this property or method." 但是当我尝试调用什么应该是一个公共方法时,我得到“对象不支持这个属性或方法。”

function NewsCalendar()
{
    var privatevar; //private vars

    this.onLoad = function () //public method
    {
        //Do Stuff
    };

    function getWeekStart(date) //private function
    {
        //Do Stuff
    }
}

The comments are there to indicate how I'm intending each item to behave. 评论是为了表明我打算如何表达每个项目。

I tried calling the onLoad function like this: 我尝试像这样调用onLoad函数:

NewsCalendar.onLoad();

But that causes the "object does not support this property or method" error. 但这会导致“对象不支持此属性或方法”错误。 I want to be able to use NewsCalendar like a namespace and be able to call any variables/methods attached to its this object by using NewsCalendar.propertyname or NewsCalendar.methodname(). 我希望能够像命名空间一样使用NewsCalendar,并且能够使用NewsCalendar.propertyname或NewsCalendar.methodname()调用附加到其对象的任何变量/方法。

You have to create instance: 你必须创建实例:

var calendar = new NewsCalendar();
calendar.onLoad();

Try the following setup: 请尝试以下设置:

var NewsCalendar = (function () {
    var privatevar;

    var onLoadHandler = function () {
        //Do Stuff
    };

    function getWeekStart(date) {
        //Do Stuff
    }

    return {
        onLoad: onLoadHandler
    };
})();

And then use: 然后使用:

NewsCalendar.onLoad();

Anything in the returned {} is public. 返回的{}中的任何内容都是公开的。 Anything inside of the surrounding function is accessible only by anything inside of it. 周围函数内部的任何内容只能由其中的任何内容访问。

The reason I suggest this setup is because you don't seem to want to instantitate several objects, but instead use it as a library of properties/methods. 我建议这种设置的原因是因为您似乎不想立即指定几个对象,而是将其用作属性/方法库。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM