我在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
如果我有主要功能:vara="foo"modify(a)fmt.Println(a)在哪里funcmodify(sstring)error{s="bar"}结果是"foo"还是"bar"? 最佳答案 没有。它不会编译,因为'foo'和'bar'都不是单个字符。但是假设您改用双引号。在Golang中,参数是按值传递的(它们被复制到内存中的新位置-堆栈或堆),无论是私有(private)方法还是公共(public)方法或任意函数都无关紧要。新实例已修改。您的示例的结果将是"foo"。为了修改位于函数外部的变量,您必须显式传递指向此类变量
我想访问名为“pastry”的包的私有(private)函数。但它会产生错误:对未导出标识符的无效引用指定在main中访问golang私有(private)函数的方式。 最佳答案 您可以使用go:linkname映射来自相同/不同包的函数到你的一些功能。例如像:packagemainimport("fmt"_"net"_"unsafe")//go:linknamelookupStaticHostnet.lookupStaticHostfunclookupStaticHost(hoststring)[]stringfuncmain()