2017-02-15 3 views
0

Ich bin gerade dabei, die Grundlagen von JS Fundamentals zu verstehen.Zugriff auf externe Funktionsvariablen von inneren Funktionen in JavaScript?

Es folgt der Code:

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 
}; 

} 

Sowohl externe Funktion und der inneren Funktionen Variablennamen sind gleiche d.h. x & y. Wie erreiche ich die externe Funktion FuncWithMathOps Variablen von inneren Funktionen SUM & MUL?

+1

Dies ist vielleicht klingen dumm verwenden, aber: Nur nicht Variablen identisch nennen, wenn Sie Zugriff haben sie über Bereiche? – Connum

+1

Dies kann auch ein Duplikat von http://stackoverflow.com/questions/8453580/javascript-callback-function-parameter-with-same-name-as-other-variable – Connum

+0

Mögliches Duplikat von [JavaScript: Callback-Funktion Parameter mit gleicher Name wie andere Variable?] (http://stackoverflow.com/questions/8453580/javascript-callback-function-parameter-with-same-name-as-other-variable) – evolutionxbox

Antwort

3

Sie können eine Variable self erstellen, die den Verweis auf this beibehalten, die später verwendet werden kann.

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))

Sie können auch .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))

Verwandte Themen