我目前正在阅读Pragmatic的一本关于Javascript的书,我对一件事感到困惑。他们有一节介绍如何使变量成为全局变量、局部变量或私有(private)变量。局部变量和私有(private)变量有什么区别?有吗?如何使一个变量成为全局变量或局部变量,他们说要在它前面加上'var=',但它非常含糊。 最佳答案 无,人们使用“private”是因为他们弄错了,意思是说“local”局部变量定义为varfoo="local";全局变量是全局作用域对象(在浏览器中是window)的一个属性window.foo="global";您可以
我是Angularjs的新手。我在网上看到一个例子,这让我很困惑。这是代码:angular.module("testApp",[]).controller("testCtrl",function($scope){vardata="Hello";$scope.getData=function(){returndata;}$scope.setData=function(newData){data=newData;}});这是View:{{getData()}}我的问题是Angular如何知道何时触发View中的getData()方法。单击事件将更改数据。然而它是一个私有(private)变
我在node.js中写的一个类如下:module.exports=exports=function(){returnnewClassA()};functionClassA(){this.myvariable=0;}我有一个我想私有(private)的函数。据我了解,如果该函数是在构造函数之外声明的,它本质上将是一个静态函数,无法引用this.myvariable。处理这个问题的正确方法是像这样在构造函数中声明函数://withinconstructorthis.myFunction=functionmyFunction(){console.log(this.myvariable)}或者
我在一个项目上工作了一段时间,试图找出我做错了什么,当我最终将“错误”缩小到以下代码无法按我预期工作的事实时:functionAlpha(){this.onion='onion';functionBeta(){alert(this.onion);}Beta();}alpha1=newAlpha();//Alerts'undefined'但是,如果我将代码更改为:functionAlpha(){varself=this;this.onion='onion';functionBeta(){alert(self.onion);}Beta();}alpha1=newAlpha();//Aler
在阅读了一些关于Javascript的prototypicalinheritancemodel之后,我从改变了构建类的风格varSome_Class=function(){this.public_method=function(){};(function(){//constructor}).call(this)}到varSome_Class=function(){(function(){//constructor}).call(this)}Some_Class.prototype.public_method=function(){};虽然我知道这是一个很好的做法,但我不能再从公共(pu
如何从JavaScript模块模式中的私有(private)函数调用公共(public)函数?例如,在下面的代码中,varmyModule=(function(){varprivate1=function(){//Howtocallpublic1()here?//this.public1()won'twork}return{public1:function(){/*dosomething*/}}})();这个问题有人问过twicebefore,每个都有不同的可接受答案。在返回之前保存对返回对象的引用,然后使用该引用访问公共(public)方法。参见answer.在闭包中保存对公共(pu
根据我对javascript的理解,原型(prototype)方法不能访问构造函数范围内私有(private)的变量,varFoo=function(){varmyprivate='Iamprivate';this.mypublic='Iampublic';}Foo.prototype={alertPublic:function(){alert(this.mypublic);}//willworkalertPrivate:function(){alert(myprivate);}//won'twork}这很有道理,但有没有什么安全且好的方法可以解决这个问题?由于使用原型(prototy
每次构建JS库时,我都有这样的概念:(function(window,undefined){varLibName=function(){varprivateAPI={method:function(){}};varpublicAPI={publicMethod:function(){}};returnpublicAPI;}window.LibName=LibName;})();但我一直渴望只是做:(function(window,undefined){varLibName=function(){varprivate={method:function(){}};varpublic={pu
我注意到我可以像这样使用私有(private)变量:varHello=React.createClass(new(function(){varname;this.getInitialState=function(){name="Sir"+this.props.name;returnnull;};this.render=function(){returnHello{name};};})());React.render(,document.getElementById('container'));为什么我不应该这样做?谢谢你的帮助 最佳答案
我想从私有(private)方法调用公共(public)方法,但属性“this”指的是窗口对象。请注意我正在尝试应用模块模式。您可以在jsfiddle.net找到工作代码示例//howcaniaccessapublicmethodfromaprivateone?//(inthisexamplepublicAlertfromprivateMethod)//thisreferstothewindowobject.$(function(){varmodulePattern=(function($){varprivateMethod=function(){appendText("calledp