2017-02-15 12 views
0

JS Fundamentalsのロープを取得しているだけで、私と一緒にいてください。続い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:with callback function parameter with他の変数と同じ名前ですか?](http://stackoverflow.com/questions/8453580/javascript-callback-function-parameter-with-same-name-as-other-variable) – evolutionxbox

答えて

3

自己を作成し、後で使用できる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))

関連する問題