2017-02-15 92 views
0

我剛剛拿到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

回答

3

您可以創建一個變量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))

相關問題