繁体   English   中英

在javascript类的子对象中访问“ this”的最佳方法是什么?

[英]What is the best way to access to “this” inside a sub object in javascript class?

这不起作用,因为f.bar.bar()未定义。

var myFunction = function(foo){
    this.foo = foo;
    this.bar = {        
        bar: function(){                
            return this.foo;
        }
   }    
}
var f = new myFunction('foo');
alert(f.bar.bar());

您始终可以在父作用域中声明一个变量:

var myFunction = function(foo){
    var func = this;
    this.foo = foo;
    this.bar = {        
        bar: function(){                
            return func.foo;
        }
   }    
}
var f = new myFunction('foo');
alert(f.bar.bar());

暂无
暂无

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

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