繁体   English   中英

这个简单的Javascript有什么问题?

[英]What's wrong with this simple Javascript?

window['TestPlugin'] = function(){
    var helloWorld = function(){
        alert('hello world');
    }
}

我尝试称其为:

$(document).ready(function () {
    TestPlugin.hellowWorld();
}

但我得到:

TestPlugin.hellowWorld不是函数

helloWorld是:

  • 在调用TestPlugin函数之前TestPlugin
  • 函数内部的局部变量,而不是函数对象的属性

为了使其成为一个属性,您需要像下面这样定义它:

window['TestPlugin'] = function(){};
window.TestPlugin.helloWorld = function(){
    alert('hello world');
}

但是由于TestPlugin并没有做任何事情,因此将其作为一个函数并没有多大意义,所以您也可以这样做:

window['TestPlugin'] = {
    helloWorld: function(){
        alert('hello world');
    }
};

调用时,还需要正确拼写。

除了[假定]错字以外,答案是: scope

helloWorld的是私人 TestPlugin等不可见之外的范围。

使此可用的一种可能方法是:

 window['TestPlugin'] = function(){ this.helloWorld = function(){ alert('hello world'); } return this; } TestPlugin().helloWorld() 

暂无
暂无

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

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