加载页面时出现控制台错误 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/