调用嵌套函数的外部函数

Calling an external function of nested function

本文关键字:函数 外部 调用 嵌套      更新时间:2023-09-26

谷歌日。

var obj = new Foo("start");   
Foo = function(some){
            this.first = function(){
                alert("First");
                $(".clazz").click($.proxy(this.second,this));
            };
            this.second = function(){
               $(".clazz").append("<span>Second</span>");
               //this.out() // Problemb with called a method "this.out()"
            };
            this.out = function(){
                $(".clazz").append("<a>Out</a>");
                // Code
            };
            this.constructor = function(some){
                this.first();
            };
            this.constructor(some);
        };

如何从方法this.second调用方法this.out?

jsfiddle

一种常见的模式是显式声明一个包含对对象引用的局部变量。这通常被称为self_this。好处是,无论其他代码做什么,您的函数都将始终绑定到您的对象。在下面的示例中,我们看到this.prop并不总是正确绑定。然而,通过仅使用self来引用对象,我们可以避免围绕此的所有问题。

JavaScript库经常使用applycall,以我们不希望的方式绑定我们的函数。

function Foo(arg1){
    var self = this;
    self.prop = arg1;
    self.first = function(){
    };
    self.second = function(){
       alert("this.prop = " + this.out() + "'n" + // 2 (baz.prop)
             "self.prop = " + self.out() + "'n"); // 1 (bar.prop)
    };
    self.out = function(){
           return this.prop; // Depends on the context, we should use self.prop
    };
}
var bar = new Foo(1);
var baz = new Foo(2);
bar.second.apply(baz);

这是一把小提琴