javascript - 无法调用 Javascript 对象方法

标签 javascript object methods

加载页面时出现控制台错误 TypeError: bodys.show is not a function。我做错了什么?

function loadingScreen(selector,css)
{
    this.loadingAnimation = $("<div><p>Loading</p><div></div></div>").appendTo(selector);
    this.containerCss = $.extend({'border-radius':"20px",position:"absolute",height:"40px",width:"120px","display":"none"}, css);
    this.loadingAnimation.css(this.containerCss);
    this.p = this.loadingAnimation.children("p").first();
    this.p.css({width:"100%",'text-align':"center"});
    this.div = this.loadingAnimation.children("div").first();
    this.div.css({position:"abslolute",left:"0",top:"0",'background-color':"rgba(255,100,100,0.5)",height:"100%",width:"10%"});
    function show(){
        this.loadingAnimation.css("display","block");
        animate(this.div,"right");
    }
    function hide(){
        this.loadingAnimation.css("display","none");
        this.div.stop(true,true);
        this.div.css("margin-left","0px");
    }
    function animate(element,direction)
    {
        if(direction === "right"){
            element.animate({"margin-left":"120px"},animate(element,"left"));
        }
        else if(direction === "left"){
            element.animate({"margin-left":"0px"},animate(element,"right"));
        }
    }
}

$(document).ready(function()
{
    var bodys = new loadingScreen("body",{});
    bodys.show();
});

最佳答案

在函数体内声明变量/函数时,它们是“私有(private)”的,除非它们作为函数本身的属性附加 - 在体内,您将使用 this关键字来执行此操作。

函数show()在 loadingScreen 内部是私有(private)的,要使其作为其父函数的成员可访问,请使用 this 声明它:

this.show  = function(){...

...}

...它仍然可以访问 loadingScreen 范围内的所有内容, 但将能够作为 loadingScreen 的方法在外部调用.

编辑:

正如 Naomik 在下面指出的,您还可以将其附加到对象的原型(prototype)上:

loadingScreen.prototype.show = function()...

...显然原型(prototype)函数比标准成员声明执行得更快,但是 - 因为您将在主函数体之外声明它,所以它无法访问函数内部的私有(private)变量,所以在这种情况下用处不大。

关于javascript - 无法调用 Javascript 对象方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21663650/

相关文章:

javascript - 使 Javascript 根据用户输入立即/立即可互换

javascript - 返回 Mongoose find() 中声明的变量

python - 保持对象在 python 的另一个程序中使用它们

java - 传递参数从mysql java检索数据的方法

java - 如何将字符串数组传递给另一个方法?

javascript - 如何从此 JSON 数组中删除不需要的元素?

javascript - Node.js 的故障 promise 复制值

java - Java 中引用属性的问题

c++ - A aaa 之间的区别;和一个 aaa();

Javascript window.open 大小无法正常工作。高度还可以,宽度有点乱