如何在JavaScript中访问父函数的公共属性?

3

我正在尝试为一个Web应用程序编写一些JavaScript函数。

根据这里的建议:如何在JavaScript中声明命名空间?

我正在尝试通过将所有内容都包装在命名函数中使代码不显眼,但是当在子匿名函数中时,访问父函数中的属性时遇到了困难。

例如:

var title_picker = new function(){
    // This property should be public
    this.callback=function(){};


    var ok=function(){
        var title = $('input#title').val();
        callback(title) // <--- 
    }
...

在“ok”函数内部,引用“callback”属性的最佳方式是什么?
2个回答

4

按照代码编写,是的,这是不可能的。

您可以访问父级范围内的变量,除非它们在较窄的范围内被覆盖。

this 总是被覆盖。

您可以将 this 复制到另一个仍然在作用域内的变量中:

var title_picker = new function(){

    var self = this; // Copy this to a variable that stays in scope

    // This property should be public
    this.callback = function(){};


    var ok=function(){
        var title = $('input#title').val();
        self.callback(title) // self is still in scope
    }
...

谢谢,看起来这个方法很好用。顺便问一下,为什么不喜欢使用new关键字呢?我对new关键字的作用有些模糊。在这种情况下,它似乎运行函数并返回其“this”作用域,这正是我想要的。(例如,能够从代码中的其他位置触发title_picker.show())。 - Chris
@Chris — 你正在使用一个函数表达式。当你调用之前定义的函数并像类一样使用时,你会使用 new … 然后,我认为你需要在那里使用 this。我从未见过有人像那样使用函数表达式 - Quentin

2
也许可以这样做:
var title_picker = new function(){
    // This property should be public
    this.callback=function(){};
    var that = this;


    var ok=function(){
        var title = $('input#title').val();
        that.callback(title) // <--- 
    }
...

虽然有很多框架可以为你完成这样的事情(如yui、dojo、prototype...)


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接