如何从JavaScript中的内部函数访问外部函数变量?

如何从JavaScript中的内部函数访问外部函数变量?

问题描述:

我刚刚拿到JS基础知识的绳索,忍受着我。如何从JavaScript中的内部函数访问外部函数变量?

以下是代码:

function FuncWithMathOps(x){ 
var x=x; 

console.log("Value of x : "+x); 

var SUM = function(x){ 
    var x=x; 

    console.log("Value of x : "+x); 
    console.log("Value of this.x : "+this.x); 
} 

var MUL = function(x){ 
    var x=x; 

    console.log("Value of x : "+x); 
    console.log("Value of this.x : "+this.x); 
} 

return { 
    SUM:SUM, 
    MUL:MUL 
}; 

} 

两个外部函数和内部函数变量名是相同的,即,x & y。如何从内部函数访问外部函数FuncWithMathOps变量SUM & MUL

+1

但这也许听起来很蠢,但是:当你要访问只是不变量的名字相同他们跨范围? – Connum

+1

这也可能是http://stackoverflow.com/questions/8453580/javascript-callback-function-parameter-with-same-name-as-other-variable的副本 – Connum

+0

[JavaScript:callback function parameter with与其他变量同名?](http://stackoverflow.com/questions/8453580/javascript-callback-function-parameter-with-same-name-as-other-variable) – evolutionxbox

您可以创建一个变量self,它将持续引用this,以后可以使用它。

function FuncWithMathOps(x) { 
 
    this.x = x; 
 
    var self = this; 
 

 
    console.log("Value of x : " + x); 
 
    var SUM = function(x) { 
 
    console.log("Value of x : " + x); 
 
    console.log("Value of this.x : " + self.x); 
 
    return x + self.x; 
 
    } 
 

 
    return { 
 
    SUM: SUM 
 
    }; 
 
} 
 

 
var fn = new FuncWithMathOps(10); 
 
console.log(fn.SUM(5))

您还可以使用.bind()

function FuncWithMathOps(x) { 
 
    this.x = x; 
 
    console.log("Value of x : " + x); 
 
    var SUM = function(x) { 
 
    console.log("Value of x : " + x); 
 
    console.log("Value of this.x : " + this.x); 
 
    return x + this.x; 
 
    } 
 

 
    return { 
 
    SUM: SUM.bind(this) 
 
    }; 
 
} 
 

 
var fn = new FuncWithMathOps(10); 
 
console.log(fn.SUM(5))