简体   繁体   English

从内部 scope 访问外部 scope

[英]Accessing outer scope from inner scope

I have a type that looks a little something like this:我有一个看起来有点像这样的类型:

var x = function(){
    this.y = function(){

    }

    this.z = function(){
        ...
        this.A = function(){
            CALLING POINT
        }
    }
}

From calling point, I'm attempting to call function this.y.从呼叫点,我正在尝试呼叫 function this.y。 I don't need to pass any parameters, but when I set some stuff from this.A, I need to call this.y.我不需要传递任何参数,但是当我从 this.A 设置一些东西时,我需要调用 this.y。

Is this possible?这可能吗? I'm OK with passing extra parameters to functions to make it possible.我同意将额外的参数传递给函数以使其成为可能。

Is this possible? 这可能吗?

Yes, you can assign this reference to another variable and then call function y on it 是的,您可以this引用分配给另一个变量,然后在其上调用函数y

this.z = function() {
    var self = this;
    this.A = function() {
        self.y();
    }
}

Version with bind , basically this adds a new method a to the object. 带有bind版本,基本上这会为对象添加一个新方法a

 var X = function () { this.y = function () { document.write('y<br>'); } this.z = function () { document.write('z<br>'); this.a = function () { document.write('a<br>'); this.y(); } }.bind(this); }; var x = new X; //xa(); // does not exist xz(); // z xa(); // ay 

Working example with saved inner this . 工作实例与保存的内this

 var X = function () { var that = this; // <-- this.y = function () { document.write('y<br>'); } this.Z = function () { document.write('Z<br>'); this.a = function () { document.write('a<br>'); that.y(); } } } var x = new X, z = new xZ; // Z za(); // ay 

Instead of function() you can try modern JavaScript or Typescript ()=> .您可以尝试现代的 JavaScript 或 Typescript ()=>而不是function() I also like .bind(this) .我也喜欢.bind(this)

You cannot because this.y() is not within the scope that this.A() is in. You can if you set this.y() to a global function y : 你不能因为this.y()不在this.A()的范围内。你可以将this.y()设置为全局函数y

var y = function() {};
var x = function() {
    this.y = y;
    this.z = function() {
       ...
       this.A = function() {
           this.y(); // will be successful in executing because this.y is set to the y function.
       };
    }
};

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

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