简体   繁体   English

如何从JavaScript中的私有函数访问公共函数

[英]How to access public function from a private function in javascript

Here is an example can anybody tell me how to do this 这是一个例子,谁能告诉我该怎么做

var calculation = function(){
    this.Add = function(){
    }
    this.Subtract(){
        var add = function(){
        //want to access Add function here
        }
    }
}

You can simply use a variable to refer to this and you can use that variable latter. 您可以简单地使用一个变量来引用this变量,然后再使用该变量。

 var calculation = function() { var _this = this; this.Add = function() { alert('In Add function'); } this.Subtract = function() { var add = function() { //want to access Add function here _this.Add(); } add(); } }; var cal = new calculation() cal.Subtract() 

Try this: 尝试这个:

vvar calculation = function(){
    this.Add = function(){
        alert("test");
    }
    this.Subtract = function(){
        this.Add();
    }.bind(this)
}

var sum = new calculation();
sum.Subtract();

http://jsfiddle.net/f6rp9mpL/ http://jsfiddle.net/f6rp9mpL/

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

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