简体   繁体   English

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

[英]How to access external function variables from inner functions in JavaScript?

Am just getting the ropes of JS Fundamentals, bear with me. 我刚刚掌握JS基础知识的绳索,请多多包涵。

Following is the 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
};

}

Both external function and inner functions variable names are same ie, x & y . 外部函数和内部函数的变量名称都相同,即xy How do i access external function FuncWithMathOps variables from inner functions SUM & MUL ? 如何从内部函数SUMMUL访问外部函数FuncWithMathOps变量?

You can create a variable self which persist the reference to this , which can be used later. 您可以创建一个变量self ,该变量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)) 

You can also use .bind() 您也可以使用.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)) 

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

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